Is snprintf (NULL, 0, ...); Is the behavior standardized?

On Linux, it returns the number of characters to be printed.

Is this a standardized behavior?

+5
source share
2 answers

Yes.

From 7.21.6.5 Function snprintf , N1570 (project C11):

The snprintf function is equivalent to fprintf, except that the output is written to an array (specified by s), not a stream. If n is zero, nothing is written and s may be a null pointer . Otherwise, output characters beyond n-1 are discarded rather than written to the array, and the null character is written at the end of the characters actually written to the array. If copying occurs between overlapping objects, the behavior is undefined.

This is a useful method for finding the length of unknown data, for which you can first find the desired length and then allocate the exact amount of memory. Typical use case:

char *p; int len = snprintf(0, 0, "%s %s some_long_string_here_", str1, str2); p = malloc(len + 1); snprintf(p, len + 1, "%s %s some_long_string_here", str1, str2); 
+8
source

According to snprintf (3) , it is standardized by POSIX and C99. This man page also says:

  Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough. POSIX.1-2001 and later align their specification of snprintf() with C99. 

So int i=snprintf(NULL, 0, " some-format-string ", .... ); should put i negative number on failure or a non-negative output file size on success.

(I don’t know exactly what will happen if the output size is larger than INT_MAX , which is very unusual, I think it will be a case of failure)

+2
source

Source: https://habr.com/ru/post/1241595/


All Articles