Aydin K.
Aydin K.

Reputation: 3367

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?

Upvotes: 0

Views: 1203

Answers (1)

nopasara
nopasara

Reputation: 536

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.

Upvotes: 1

Related Questions