Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault when using double brackets with printf [duplicate]

#include<stdio.h>
#define POOLNAME_FMT "Hello"

void main() {

 printf((POOLNAME_FMT "Cannot allocate %d bytes" POOLNAME_FMT "in pool not enough memory",5));

}

Why does it give segmentation fault when I use double brackets with printf. i.e. printf(( ));?

like image 604
Hemant Parakh Avatar asked Nov 30 '22 11:11

Hemant Parakh


1 Answers

Because (a, b) is actually a single value. It calculates a and b and returns the value of b.

So what you are doing is basically:

/* calculate before `,` and ignore */
POOLNAME_FMT "Cannot allocate %d bytes" POOLNAME_FMT "in pool not enough memory";
/* call printf with after `,` */
printf(5);

Which is clearly wrong.


When you write func(a, b) as a function call, C knows to send a and b as separate arguments to func. When you say func((a, b)), you are explicitely saying (a, b) is one value and that the result (i.e., the value of b) should be sent to func as a single argument.

If you compile with warnings, and if your compiler is nice to you, it could warn you about this. If your compiler is not nice, it should still complain that you are giving an int where a const char * is expected.

If using gcc, I highly recommend compiling with -Wall, always.

like image 113
Shahbaz Avatar answered Dec 05 '22 03:12

Shahbaz