seems its a feature of gcc. In certain circumstances it optimizes the printf call to a puts call. While printf behaves nicely and prints '(null)' when you pass it a null pointer, puts doesnt do that. From the document above when "%s\n" is found in the format string it is optimized to a puts call. Its interesting to note that the optimization is disabled if the printf return value is assigned. So
replacing
printf("%s\n",p);
with
ret=printf("%s\n",p);
doesn't segfault.
-Ershaad
On Wed, Jun 18, 2008 at 3:22 PM, Wang Yu <wangyuict@xxxxxxxxx> wrote:
Hi, all
I have the following code:
#include <stdio.h>
int main()
{
char *p;
p = 0;
printf("%s", p);
printf("\n");
return 0;
}
The out put is (null)
But, if I change into:
#include <stdio.h>
int main()
{
char *p;
p = 0;
printf("%s\n", p);
return 0;
}
The output will be Segment fault!
I don't know why....
Thanks!
--
National Research Center for Intelligent Computing Systems
Institute of Computing Technology, Chinese Academy of Sciences