Quote:Original post by smr
This can prevent some buffer overrun errors as long as you adhere to that length.
Actually, in the case of a potentially insecure source (i.e. if you are reading from the network or a file can be modified), this can _cause_ buffer overrun errors. The ASN.1 data format (used by SNMP and a number of other protocols) uses this method, and is notoriously insecure because of it. If you really want to mess up that peice of code you have, create a file and modify the length field to be -1. Or put in a really long string and say that the length is 1. Much havoc may ensue. In a simple program, it will probably just cause a crash or give you invalid data (which is a possibility no matter what format you use), but in a complicated server application it can be a severe security hole.
Of course, if you can place a sane limit on the length of a string (for example say that monster names can be no longer than 64 characters), it is very easy to work around this problem and detect invalid data.
And if you're worried about buffer overflow problems with writing a structure binary to the file, just assign the last byte in the string to be null after you fread from the file (which you should probably make sure you do anyway). Placing a structure binary in a file is not always the best solution for a production product. However, if you're lazy it can be a quick easy temporary solution