This is my code snippet in C:
char *str = NULL;
int len = -1;
// Get length
len = snprintf(NULL, 0, "[%d]", 2);
// Allocate str
str = (char *)malloc(len + 1);
// Assign str
snprintf(str, len, "[%d]", 2);
assert(len == 3);
// Display str
puts(str);
I expect this should display [2]
. And len
here is 3.
But running this code displays only [2
Why is this so?
The length of the buffer is len+1
, but you only pass len
to snprintf
, try this:
snprintf(str, len + 1, "[%d]", 2);
from cplusplus.com:
If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function.
A terminating null character is automatically appended after the content.