does snprintf guarantee null termination?

Hi All,

I was reading the man page of snprintf function and it saids that snprintf adds a null terminator at the end of the string, but I remember once someone told me that snprintf doesn't guarantee the insertion of a null terminator character.

What do you think? Does anyone have experience on it??

Thanks!!

According to POSIX.1-2001:

"The snprintf() function shall be equivalent to sprintf(), with the addition of the n argument which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may be a null pointer. Otherwise, output bytes beyond the n-1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array."

What the OP is on about:

from the same C-99 standard (what POSIX uses)

So you have to check the return code of snprintf to know if it worked correctly.
You should check return codes no matter how stupid it seems. If you use gcc then

gcc -Wall <filename.c> 

or use lint on your code. The only acceptable compile is a completely clean one.

Hi,

I also was reading that in another not UNIX operating systems (i.e. window$) sprintf doesn't guarantee the insertion of a null terminator, hence my confusion!

Thank you very much!

I would rely on the manpage of snprintf() on your system instead of on a certain someone. You can write a small code snippet to verify if snprintf() provides that functionality.