Search code examples
cprintfputs

C - not output after snprintf


I'm doing my first steps with C (pointers, pointer-pointer etc, I love it), so have mercy if this is a dumb question.

This fragment outputs nothing:

char buf[256];
snprintf(buf, sizeof buf, "output: %s%s%s");

puts("test");

And this fragment outputs "test" (as expected):

char buf[256];
snprintf(buf, sizeof buf, "output: %s%s");

puts("test");

=>test

Question: Which role does snprintf play here? Is there any relationship with the puts-statement or why has the puts no effect/output in the first code?


Solution

  • Because snprintf(buf, sizeof buf, "output: %s%s%s"); requires 3 parameters :

    snprintf(buf, sizeof buf, "output: %s%s%s", str1, str2, str3);

    and snprintf(buf, sizeof buf, "output: %s%s"); requires 2 parameters:

    snprintf(buf, sizeof buf, "output: %s%s", str1, str2);

    if you don't pass parameters to snprintf function doesn't mean snprintf wont try to access them. So, the result you see is a segmentation fault result caused by snprintf trying to access "str3" parameter that doesn't exist.