Reputation: 36441
On Linux it returns the number of characters that would be printed.
Is this standardized behavior?
Upvotes: 15
Views: 4107
Reputation: 121407
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);
Upvotes: 15
Reputation: 1
According to snprintf(3) it is standardized by POSIX & by C99. That 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 in i
a negative number on failure, or a non-negative output size on success.
(I don't exactly know what happens if the output size is bigger than INT_MAX
which is very unusual; I guess that it would be a failure case)
Upvotes: 3