4 ms·
Why doesn't the standard library warn when it knows %Lf might be too long?
by iso8859-1 13y ago
Why doesn't the standard library warn when it knows %Lf might be too long?
- asveikau 13y agosprintf does not know the size of the destination buffer. That's why the newer snprintf, which takes a size as a 2nd parameter, is recommended. (I say newer, but according to manpages snprintf is defined by SUSv2, from 1997, and C99, from 1999; so they're pretty old by now.) You could probably have the compiler warn, provided (1) the destination is still an array and not a pointer (2) the format string is known at compile time. But that's a very different thing. (Most compilers these days do warn about any calls to sprintf, recommending snprintf instead.)
- zwp 13y ago> newer snprintf Also see C11's sprintf_s() and similarly-named friends.
- asveikau 13y agoThis is one area where C11 seems like it solves pointless non-problems. snprintf() is not all that "unsafe" in that it does do a bounds check, and the C99 version is clear about saying that the null terminator is included in the count. I also like the error conditions of C99 snprintf() better - it's more interesting to know the exact size required than it is to know that my buffer is not big enough.