Aydin K. Aydin K. - 1 year ago 78
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download