The glibc printf %s allows NULL as a parameter while puts() does't so gcc should not convert the printf to puts unless it is certain that the parameter is not null. On the other hand if the parameter is certainly null one could call puts("(null)"); See also: bug #15574 Example code: % cat > bug.i << EOF extern int printf (__const char *__restrict __format, ...); int main () { printf ("%s\n", ((void *)0)); return 0; } EOF % gcc bug.i % ./a.out (null) % gcc bug.i -O % ./a.out segmentation fault
Not a bug as printf can segfault if it is supplied a NULL pointer for the string formatter. If glibc does something different than that, glibc is does not have a bug either as it is undefined really so converting the call to a puts is a vaild transformation.
*** Bug 25609 has been marked as a duplicate of this bug. ***
(In reply to comment #1) > Not a bug as printf can segfault if it is supplied a NULL pointer for the > string formatter. > If glibc does something different than that, glibc is does not have a bug > either as it is undefined really > so converting the call to a puts is a vaild transformation. > Even if its a valid transformation, there is the question if this is a reasonable transformation. Obviously that optimization was introduced because quite alot of people do not know about the puts function and use printf to output static lines of text. On the other hand there are people who rely on glibc's handling of the undefined NULL pointer situation. Question is: Which group is bigger. The missuse printf as puts group or the rely on glibc's relaxed NULL handling group. My guess would be that people who do not even know puts care even less about the fact that ANSI and ISO didn't care about NULL handling in format strings. If that would true, this optimization would be valid, but unreasonable as it breaks the expections of your clients.
(In reply to comment #4) > Question is: Which group is bigger. The missuse printf as puts group or the > rely on glibc's relaxed NULL handling group. My guess would be that people who > do not even know puts care even less about the fact that ANSI and ISO didn't > care about NULL handling in format strings. If that would true, this > optimization would be valid, but unreasonable as it breaks the expections of > your clients. The expectations of our "clients" is to follow standards while producing fastest code possible. Glibc behaviour is inconsistent here. In principle there should be no difference between puts(s) and printf("%s",s) and fprintf(stdout, "%s", s). Imagine that the two last ones did something different (I haven't tested, so they actually may) when s == NULL, wouldn't you consider it glibc's fault? Then, why you don't request the same for puts(s)?
Just for reference. Neither fprintf() nor sprintf() seem to follow the behaviour of printf() in glibc 2.5.