Damn while loop Parsing
Can you tell me that you have found an error?
If you have found an error, skip this article. This article does not apply to you.
According to the text stipulated in the agreement, there should be no errors in this program. Why?
Agreement and agreement-Agreement + negotiation indicates that this item can be negotiated. Who can ensure that all program designers are consistent with the Agreement text in all the details? In the final analysis, the agreement is still made by people. Who can ensure that there is no defect in the first formulation? There are not many unspecified terms in the standard text of early C, so now the compiler supports their respective States, and everyone should have a very bad experience.
After a while, in the final analysis, no one can ensure that all programs can work in the protocol text, and no one can ensure that the content is rewritten in some circumstances (of course, there should be other means, not described here)
As long as a simple instance is faulty.
Uslename = 100
Tag Len cont tag Len?
Aucbuffer = {0x01, 0x03, 0x00, 0x02, 0x00, 0x01, 0x02 ,...}
Obviously, the error is
Usoffset + = aucbuffer [usoffset + 1];
If aucbuffer [usoffset + 1] = 0, the great endless loop is born.
What should I do? To address this problem, I recommend the following:
Usoffset = 0;
Uscount = 0;
While (usoffset <uslen)
...{
/** // * Record tag */
Msgcontent [uscount]. Tag = aucbuffer [usoffset];
/** // * Record the content length of the tag */
Msgcontent [uscount]. Len = aucbuffer [usoffset + 1];
/** // * Record the address of the tag. Note that the content will not be copied here and will be retrieved in actual use */
Msgcontent [uscount]. content = usoffset;
/** // * If the tag length is smaller than the minimum possible length, it jumps out and the decoding fails */
If (aucbuffer [usoffset + 1] <2)
...{
Break;
}
/** // * Decode the offset of the next tag */
Usoffset + = aucbuffer [usoffset + 1];
/** // * Number of record tags */
Uscount ++;
}
If (usoffset <uslen)
...{
Return Error;
}
To illustrate the problem, the code is very simple and may be considered during writing. But can these exceptions be considered even if the complexity of the Code increases by N times?
This method solves the issue of endless loops. But is it foolproof? Please refer to the following.