Monday, October 21, 2019

gcc: using snprintf to append strings does not work


Considering this piece of code:

#include <stdio.h>

int main()
{
  char buf[1000];

  snprintf(buf, sizeof(buf), "%s", "Hello World");
  printf("%s\n", buf);

  // trying to append 1024 to the string.
  snprintf(buf, sizeof(buf), "%s%d", buf, 1024);
  printf("%s\n", buf);
}

One may expect the second printf will output a string of "Hello World1024". However, for the latest versions of the GCC, you may get the following output from the code:

Hello World
1024

The second printf only prints out "1024".

No comments:

 
Get This <