Yesterday, a colleague asked me if the end of snprintf must be '\ 0'. I have seen that strncpy does not necessarily end with' \ 0. It seems inappropriate to get up early today. Just try it. The following is the result.
Test code
#include <stdio.h>int main(void){ char szBuf[10] = {0}; snprintf(szBuf, sizeof(szBuf), "1234567890"); printf(szBuf); printf("\n"); if (szBuf[9] == '\0') { printf("null end\n"); } return 0;}
Environment 1
SunOS solx55 5.10Generic _ 144489-17 i86pc i386 i86pc
Result
User % a. out
123456789
Null end
Man Manual
The snprintf () function is identical tosprintf () with
Addition of the argument n, whichspecifies the size of
Buffer referred to by s. If n is 0, nothing is written and s
Can be a nullpointer. Otherwise, output bytes beyond
N-1st are discarded instead of being written to the array
And a null byte is written at theend of the bytes actually
Written into the array.
Environment 2
User % uname-
Linux rhel65 2.6.32-131.0.15.el6.x86 _ 64 # 1SMP Tue May 10 15:42:40 EDT 2011 x86_64 x86_64 x86_64 GNU/Linux
Result
User % a. out
123456789
Null end
The Administrator does not have an installation manual, so there is no man manual.
Environment 3
User @ ibm182 ~ $ Uname-
AIX ibm182 3 5 00033CE7D600
User @ ibm182 ~ $ A. out
123456789
Null end
Man Manual
The snprintf subroutine converts, formats, and stores the Value parameter values, under control of the Format parameter, into consecutive bytes, starting at the address specified by the Stringparameter. the snprintf subroutine places a null character (\ 0)
At the end. Youmust ensure that enough storagespace is available to contain the formatted string
With the addition ofthe Number parameter, which statesthe size of the buffer referred to by the String parameter.
Environment 4
User % uname-
HP-UX hp12162 B .11.31 U ia64 0887221123 unlimited User License
Result
User % a. out
123456789
Null end
Man Manual
Snprintf () behaves like sprintf (), effectthat it limits the number
Characters written to the destination buffer to maxsize, including
Terminating null character.
Obviously, all four environments end with '\ 0', and Windows platforms will not be tested.