Bug 10818 - printf("%s\n", NULL) segfaults
Summary: printf("%s\n", NULL) segfaults
Status: RESOLVED DUPLICATE of bug 5618
Alias: None
Product: glibc
Classification: Unclassified
Component: libc (show other bugs)
Version: 2.9
: P2 normal
Target Milestone: ---
Assignee: Ulrich Drepper
Depends on:
Reported: 2009-10-21 07:14 UTC by Kir Kolyshkin
Modified: 2014-07-01 05:36 UTC (History)
1 user (show)

See Also:
Last reconfirmed:
fweimer: security-


Note You need to log in before you can comment on or make changes to this bug.
Description Kir Kolyshkin 2009-10-21 07:14:32 UTC
[kir@kir ~]$ cat null.c 
#include <stdio.h>

int main(void) {
	fprintf(stdout, "%s\n", NULL);
	printf("%s%s\n", NULL, NULL);
	printf("%s", NULL);
	printf("%s\n", NULL);
	return 0;
[kir@kir ~]$ gcc null.c
[kir@kir ~]$ ./a.out 
Segmentation fault

Note that only printf with "%s\n" segfaults, while others are fine.

This is because 
(1) call to printf("%s\n", str) is optimized to puts(str)
(2) puts(str) calls strlen(str)
(3) strlen(NULL) segfaults

System info:

$ rpm -q fedora-release gcc glibc

I discovered this bug when trying to do something like this:

	/* This should return NULL -- buflen is not big enough */
	printf("%s\n", inet_ntop(AF_INET, &in, buf, 2);

and got SIGSEGV instead of (null) being printed.
Comment 1 Kir Kolyshkin 2009-10-21 07:45:36 UTC
Relevant GCC bug:

Relevant portion of glibc doc [1]:
> If you accidentally pass a null pointer as the argument for a ‘%s’
> conversion, the GNU library prints it as ‘(null)’. We think this
> is more useful than crashing. But it's not good practice to pass
> a null argument intentionally. 

Comment 2 Kir Kolyshkin 2009-10-21 10:45:52 UTC
Yet one more relevant bug to gcc:

From my perspective the best thing to do is to let puts with NULL argument to
print "(null)\n", just for the consistency with printf's behavior, and with a
"side effect" of fixing this bug (caused by gcc optimization, but nevertheless).
Comment 3 Jakub Jelinek 2009-10-21 10:48:53 UTC
You don't understand.  The bug is in our code, not in glibc.
Comment 4 Kir Kolyshkin 2009-10-21 10:53:19 UTC
OK, basically this is a dup of bug #5618, let's mark it as such...
Comment 5 Kir Kolyshkin 2009-10-21 10:53:31 UTC

*** This bug has been marked as a duplicate of 5618 ***
Comment 6 Manuel López-Ibáñez 2009-10-21 11:49:23 UTC
(In reply to comment #3)
> You don't understand.  The bug is in our code, not in glibc.

All related bugs are closed as INVALID. So nobody thinks there is a bug at all.