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 NULL
pointer as argument to a printf
with %s
specifier is undefined behavior1 (i.e. anything can happen), so both behaviors are licit.
In the first case, the standard library (in particular, the printf
code) is doing you a favor by printing (null)
.
In the second case, instead, the optimizer understands that your printf
can be replaced by a puts
(which is more efficient) without any change to the "observable behavior" of the program, and so it replaces it. But, puts
does not happen to contain the NULL
-checking code of the printf
, and thus you get a segmentation fault.
C99, §7.19.6.1, ¶8:
the argument shall be a pointer to the initial element of an array of character type.
¶9:
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
You fall in this last case, because NULL
is not "a pointer to the initial element of an array of character type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With