37 points · by pcr910303 · 4y ago · 24 comments
You have a function that takes char *endptr and passes *endptr to isspace(). At least on the particular version of the MSVC compiler I usually use, char is signed by default, and isspace uses an ASCII lookup table internally, presumably 256 bytes long.
So if anything passes a so-called "negative ASCII" value to your routine, memory will be accessed prior to the beginning of the table. Usually just causes a crash, but the implications could go well beyond that. Whenever I use any of the is...() functions, I've learned to cast the value to unsigned char to make sure underflow can't happen. It's caused a lot of bug reports from non-US-based users who end up with ANSI (extended or 'negative' ASCII) characters in various places.
Obviously there are plenty of facepalms to go around here, ranging from the C standard's failure to disallow signed chars to certain compilers' adoption of them, to Microsoft's failure to protect their standard C library function inputs, to my negligence in not realizing the implications of the foregoing. Definitely something to watch out for in your own code.
As I write this, it occurs to me that they might actually use a 128-byte LUT. So I should either stop using iswhatever() functions altogether or write my own wrapper for them....
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
IOW, you invoked undefined behavior. That's one of the problems with the C standard library: it expects callers to be much more careful than the language wants you to. So many footguns. It doesn't help that the implementations of the standard library assume the callers are doing their due, mostly for speed reasons that were valid 20+ years ago.And, given that behavior, that the documentation fails to explicitly call it out is borderline malicious. Given that the authors even knew about it, which I guess is doubtful.
As another example, notice that abs(number) has Undefined Behaviour for INT_MIN or whatever C calls it.
I think it is more likely the same issue Posix had, the official standard came after the implementations. So it had to unify all existing implementations under the same definition. Which means the standard could not require sane behavior if even a single implementation failed to validate its input or two implementations disagreed on the exact error.
"POSIX has become outdated" 2016 paper,
https://www.usenix.org/publications/login/fall2016/atlidakis
I do wonder why they didn't have the function take an unsigned int, or at least do a simple bitwise AND with 0xFF before the table lookup.