Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two cases while trying to print NULL, one works, other SegFaults

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.

like image 923
noMAD Avatar asked Apr 10 '12 21:04

noMAD


1 Answers

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.


  1. 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.

like image 101
Matteo Italia Avatar answered Oct 12 '22 22:10

Matteo Italia