Šimon Tóth
Šimon Tóth

Reputation: 36451

Is printing NULL string defined?

Does this code have defined behaviour?

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

In context of C++ (98/03 and 11) and C (99) standards.

Upvotes: 3

Views: 4118

Answers (3)

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16617

De-referencing a null pointer in C produces undefined behavior, which could be catastrophic. However, most implementations simply halt execution of the program in question, usually with a segmentation fault.

Please check this

Upvotes: -1

codaddict
codaddict

Reputation: 455282

Yes.

printf will dereference the pointer str and dereferencing a NULL pointer is UB.

Upvotes: 2

ouah
ouah

Reputation: 145899

undefined behavior in C

(C99, 7.19.6.1p8) "s If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type."

with some compilers / libc it prints (null) and with some other it segfaults.

(Note: in C violation of a shall that is not a constraint is undefined behavior, see 4.p2 "Conformance" in Standard C)

Upvotes: 5

Related Questions