Aydin K. Aydin K. - 7 months ago 40
C Question

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");


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

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



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?


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.