1

Thanks first for your time spent here. I have a question with snprintf() when size=0, with code below:

#include <stdio.h> #include <stdlib.h> int main(int ac, char **av) { char *str; int len; len = snprintf(NULL, 0, "%s %d", *av, ac); printf("this string has length %d\n", len); if (!(str = malloc((len + 1) * sizeof(char)))) return EXIT_FAILURE; len = snprintf(str, len + 1, "%s %d", *av, ac); printf("%s %d\n", str, len); free(str); return EXIT_SUCCESS; } 

when I run:

momo@xue5:~/TestCode$ ./Test_snprintf 

The result is:

this string has length 17 ./Test_snprintf 1 17 

What confuses me is in the code, the size to be written is 0, why displayed 17?

What did I miss?

Thanks~~

1 Answer 1

2

The solution can be found in the man page under Return value;

The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.

This is so that you can do exactly what you do, a "trial print" to get the correct length, then allocate the buffer dynamically to get the whole output when you snprintf again to the allocated buffer.

Sign up to request clarification or add additional context in comments.

1 Comment

@momoxinduo You pass NULL in to only get the length so that you can dynamically allocate memory for doing the real print. Exactly what your code is doing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.