In the following:
printf("Example%s\n",NULL);
printf("%s\n",NULL);
I get the output as:
Example(null)
Segmentation Fault
When I tried backtrace in GDB it shows printf() is converted to puts(). But I can’t seem to understand why this happens.
BTW I found this article but still can’t seem to make sense.
The standard says that passing a
NULLpointer as argument to aprintfwith%sspecifier is undefined behavior1 (i.e. anything can happen), so both behaviors are licit.In the first case, the standard library (in particular, the
printfcode) is doing you a favor by printing(null).In the second case, instead, the optimizer understands that your
printfcan be replaced by aputs(which is more efficient) without any change to the “observable behavior” of the program, and so it replaces it. But,putsdoes not happen to contain theNULL-checking code of theprintf, and thus you get a segmentation fault.C99, §7.19.6.1, ¶8:
¶9:
You fall in this last case, because
NULLis not “a pointer to the initial element of an array of character type.