TIL C11 Annex K exists but you shouldn't use it

submited by
Style Pass
2024-10-31 22:30:03

Annex K is the technical name. Other common keywords are __STDC_LIB_EXT1__ and __STDC_WANT_LIB_EXT1__. Annex K defines the "secure" _s suffix stuff like sprintf_s() and scanf_s().

What's the point of the _s() functions? They check their arguments for more invariants like "will call the constraint handler if the stream is null, the string is null, the bufsz is zero, or the buffer would write out-of-bounds beyond the specified length". That seems like a good idea, right? Yeah! It does!

Notice how the normal fopen() has the same return value (possibly different errno) to indicate different levels of bad-ness of errors? That's kinda what this fopen_s() was trying to improve. At least, that's my reading of it. I think of it like Rust's panic!() vs a returned Result<String, std::io::Error>. It also probably helps stop some buffer overflow attacks by providing size_of_dest arguments to avoid overflowing any dest buffers like strcpy_s() and gets_s().

Reads stdin into the character array pointed to by str until a newline character is found or end-of-file occurs. A null character is written immediately after the last character read into the array. The newline character is discarded but not stored in the buffer.

Leave a Comment