6 ms·
Could you elaborate on why "treating the pointer to a string and the string length as separate vars" is dangerous to someone who hasn't done a lot of C?
by code_sloth 9y ago
Could you elaborate on why "treating the pointer to a string and the string length as separate vars" is dangerous to someone who hasn't done a lot of C?
- pabl0rg 9y agoIf you access a memory location beyond the end of the string, you can get all sorts of unexpected behavior. The string's length is something you'll pretty much always need to take into account.
- DaiPlusPlus 9y agoMany libraries and systems (e.g. Win32) just go with null-terminated strings and their functions don't accept a length argument at all - so I wonder if some people never store the length simply because they don't believe they'll ever need it.
- qb45 9y agoBecause occasionally you use wrong length with wrong pointer and read or overwrite something you didn't want to. It's more convenient and safer to have these two variables packed together as a "string object" and have string functions operate on that - then they always know where the string starts and ends in memory.
- geofft 9y agoBasically, it encourages you to store only the string pointer and re-calculate the length (or let a library function do so) or use the wrong length value, which means if there's some specific length or capacity worth paying attention to, it's easy to get it wrong. Really you want both a length, of the data actually in the string, and a capacity, marking how much memory is valid. If I'm understanding the vulnerability right: strncmp takes three arguments, the beginning of the first string, the beginning of the second string, and the maximum number of bytes to compare. That maximum isn't quite a length or a capacity. It's a bound on the length, if one of the strings isn't null-terminated. But if you provide too small a maximum, it'll only compare the first few characters, and return a value based on that. In particular they compared the target string to the user-provided string, with a user-provided length, so if you provide an empty string, it compares 0 bytes and returns success. An API of the form strcmp(struct actual_string a, struct actual_string b) wouldn't have this problem - the actual string structures (instead of a char pointer) would provide a length for both strings, so the API wouldn't let you make this sort of error.