> this might be a strange question, but why is snprintf not guaranteed to
> nul terminate a string?
History, mostly.
As I see it, there are two ways to go when the string being written exceeds
the space avaialble to it.
1) truncate and null terminate
2) just truncate
C has always had the mindset that the programmer knows what he is doing or
should know. So, it chooses option 2.
> i thought the whole point of those sn functions was to prevent these
> errors.
You may be thinking of the new "safe" string functions
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/sec
ure03102004.asp
> sure, they prevent buffer overwrites, but callers can still screw up bad
> if they don't always make sure for themselves that the 0 is there before
> they let someone else read the contents.
Yup. The docs do mention in their security note that
snprintf(s, ...)
should be followed by
s[n - 1] = 0;
where n = the number of characters in s.
> now you still have the problem that you have to make that check
> everywhere, instead of not having to bother.
Yup. Sadly, such is life. Since C "strings" are just arrays, and since
"strings" are passed by simple pointer, called functions have no
authoritative source for string length.
Regards,
Will
> Hi,
>
[quoted text clipped - 11 lines]
> kind regards,
> Bruno.
Hi Bruno,
Take a look at the following link:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/sec
ure03102004.asp
Ronald Laeremans
Visual C++ team