Is snprintf() ALWAYS null terminating?

前端 未结 5 780
终归单人心
终归单人心 2020-11-28 06:55

Is snprintf always null terminating the destination buffer?

In other words, is this sufficient:

char dst[10];

snprintf(dst, sizeof (dst), \"blah %s\         


        
5条回答
  •  遥遥无期
    2020-11-28 07:32

    According to the C standard, unless the buffer size is 0, vsnprintf() and snprintf() null terminates its output.

    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.

    So, if you need to know how big a buffer to allocate, use a size of zero, and you can then use a null pointer as the destination. Note that I linked to the POSIX pages, but these explicitly say that there is not intended to be any divergence between Standard C and POSIX where they cover the same ground:

    The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard.

    Be wary of the Microsoft version of vsnprintf(). It definitely behaves differently from the standard C version when there is not enough space in the buffer (it returns -1 where the standard function returns the required length). It is not entirely clear that the Microsoft version null terminates its output under error conditions, whereas the standard C version does.

    Note also the answers to Do you use the TR 24731 safe functions? (see MSDN for the Microsoft version of the vsprintf_s()) and Mac solution for the safe alternatives to unsafe C standard library functions?

提交回复
热议问题