0
char *p = NULL;
printf("%s", p); 

Why does above does not lead segmentation fault? But

char *p = NULL;
printf("%s\n",p); 

does?

To add i know it is undefined behavior to use in this way but still wondering why does it generates segmentation fault 6 out of 6 times with \n while not without it.

I was asked this question in interview and i gave same answer as its undefined behavior but their expectation was to give reason for it and i do not know what else can i add. Any thoughts on it?

nonenone
  • 120
  • 1
  • 3
  • 9
  • 5
    Passing a NULL pointer to `printf()` invokes Undefined Behaviour. You are lucky the behaviour **was** different for the two situations: you got to notice it and ask why. But there is no reason other than it's undefined. Don't do it. – pmg Mar 29 '14 at 15:21
  • 1
    Referring to invalid memory is undefined behavior, it has nothing to do with `\n`. – Rohan Mar 29 '14 at 15:21
  • 2
    Passing a NULL pointer to `printf()`is fine. Just don't pass it off as a valid string or such. Lying is frowned upon, the penalty being UB. – Deduplicator Mar 29 '14 at 15:27
  • 1
    This shows how seemingly unrelated change can influence undefined behavior (for better or worse). – user2802841 Mar 29 '14 at 15:27
  • This question lacks a complete repro test case along with detailed platform notes. That basically makes it an open-ended debate question. Hence, voting to close as "primarily opinion-based". – Kaz Mar 29 '14 at 16:29

3 Answers3

5

A great example of undefined behaviour. You're passing a NULL-pointer to printf where it expects a pointer to a null-terminated character buffer, the behaviour of which is not defined. This means that only the goblins in the machine know what is going to happen. Sometimes it seems to work, sometimes it doesn't, sometimes it gives an error and other times it'll just crash.

The moral of the story is: don't invoke undefined behaviour; don't pass a NULL-pointer to printf.

Kninnug
  • 7,992
  • 1
  • 30
  • 42
1

Both your examples invoke UB, because the format string leads printfto expect a valid string, while you supply a (char*)0.

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
0

you yourself giving an excellent example of undefined behaviour.what is the need of passing NULL pointer to the printf(),do someone force you? As the name suggest it is behaviour of
The incorrect codes to which standard forces no requirements

It can even launch mesilles unwillingly if you have sufficient hardware
Read more from the links specified in the Kninnug answer.

OldSchool
  • 2,123
  • 4
  • 23
  • 45