Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

standards

stdio

On Linux it returns the number of characters that would be printed.

Is this standardized behavior?

like image 935
Šimon Tóth Avatar asked Jan 27 '16 11:01

Šimon Tóth


People also ask

Is Snprintf always null terminated?

snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero.

What does Snprintf do in C?

The snprintf() function formats and stores a series of characters and values in the array buffer. The snprintf() function accepts an argument 'n', which indicates the maximum number of characters (including at the end of null character) to be written to buffer.

What is the difference between Sprintf and Snprintf?

The snprintf() function is identical to the sprintf() function with the addition of the n argument, which indicates the maximum number of characters (including the ending null character) to be written to buffer.


1 Answers

Yes.

From 7.21.6.5 The snprintf function, N1570 (C11 draft):

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

It's a useful method to find the length of unknown data for which you can first find the necessary length and then allocate the exact amount of memory. A typical use case is:

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);
like image 81
P.P Avatar answered Oct 09 '22 17:10

P.P