Are snprintf and friends safe?

Recently there was a question about SO ( Why would anyone use strncpy instead of strcpy? ) That got the answers ( answer 1 , answer 2 ), this made me unsure about other string functions with "n" in their name, like snprintf (which I am widely used). Is it safe to use snprintf? In general, what are the safe functions from the "n" family?

+4
source share
5 answers

strncpy() is an odd function that is actually incorrectly named - its original purpose is to make sure that the buffer is fully initialized with the contents of the string (without overflowing the target) and a buffer reminder with zeros. As far as I understand, the original goal was to process the file system directory entries - the target buffer was not really a string in the same sense as the other strxxx() functions in the C library. The main problem with strncpy() is that if the source string is larger than the destination buffer, the result will not be null.

Most of the other "n" functions that deal with strings do end the string, but there are exceptions, such as Microsoft bastardized _snprintf() . The correct C99 snprintf() will always have zero termination of the target string (as long as the destination buffer is larger than 0).

There is a "Technical Report", TR 24731, which offers a set of alternative border checking options for functions related to lines and memory buffers. One of the goals of TR is to make the parameters, results, and error behavior of functions more similar in function. TR seems to have a bit of mixed recognition, and I don't think it is widely implemented except for the Microsoft compiler (I think MS was the main TR driver). You can get more information here:

Even if you are not a fan of these suggestions, I think that they make problems with existing functions for educational reading.

+13
source

Until snprintf overflows the buffer, if you give it the correct arguments, remember that it shares all vulnerabilities of the format string with other members of the *printf family. For example, the %n specifier is unpleasant because it can be used by attackers to write arbitrary bytes to arbitrary memory cells. See FIO30-C. Exclude data entry from format strings from CERT C wiki pages.

+1
source

This is safe because you provide the correct buffer length.

0
source

snprintf does guarantee that the buffer will not be overwritten, but it does not guarantee zero completion. You can use sprintf_s in MSVC if you want to be custom.

See http://msdn.microsoft.com/en-us/library/2ts7cx93(VS.71).aspx

-1
source

Beware: different platforms have different types of behavior regarding the null termination of the string passed to snprintf .

-2
source

All Articles