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
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2009-10-21 07:14 UTC by Kir Kolyshkin
Modified: 2014-07-01 05:36 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:
fweimer: security-


Attachments

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("\n-newline-\n");
	printf("%s\n", NULL);
	return 0;
}
[kir@kir ~]$ gcc null.c
[kir@kir ~]$ ./a.out 
(null)
(null)(null)
(null)
-newline-
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
fedora-release-10-1.noarch
gcc-4.3.2-7.x86_64
glibc-2.9-3.i686
glibc-2.9-3.x86_64

PS
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:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=15685

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. 

[1]
http://www.gnu.org/software/libc/manual/html_node/Other-Output-Conversions.html#Other-Output-Conversions
Comment 2 Kir Kolyshkin 2009-10-21 10:45:52 UTC
Yet one more relevant bug to gcc:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25609

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.