0

I ran the following tests on my linux box.

test 1:

printf("test %s\n", NULL);
printf("test %s\n", NULL);

prints:

test (null)
test (null)

test 2:

printf("%s\n", NULL);
printf("%s\n", NULL);

prints

Segmentation fault (core dumped)

What is the difference in the above tests? Why is segmentation fault not thrown in test 1 above?

I was not able to understand why in the second test, it is failing to print?

kadina
  • 5,042
  • 4
  • 42
  • 83

1 Answers1

2

Enable the warnings in your compiler. You are not printing what you think you are.

My compiler would be happy to inform you that (in both cases):

warning: reading through null pointer (argument 2) [-Wformat]
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘void *’ [-Wformat]

As Red Alert says, ALERT!, what you do is undefined behaviour.

Moreover, make sure to check the linked answer for a more detailed answer, which is not far from mine.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • @kadina, I see that you got a -2, while the linked answer I posted, has a +8. I think this happens because, there was already an answer, but you didn't look for that. I will you a +1 for balance, but make sure you search better next time. :) – gsamaras Sep 25 '14 at 23:02