3

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?

pmg
  • 106,608
  • 13
  • 126
  • 198
Neigyl R. Noval
  • 6,018
  • 4
  • 27
  • 45
  • 1
    Please [don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169). – unwind Apr 02 '13 at 09:13

2 Answers2

11

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.

MByD
  • 135,866
  • 28
  • 264
  • 277
0

The functions snprintf() write at most len bytes (including the terminating null byte ('\0')) to str.

len equal to 3 (the first call), so snprintf will write only 3 char: '[', '2' and '\0'.

Bechir
  • 987
  • 10
  • 26