Home > Mobile >  Why are glibc printf()-functions inconsistent about null pointer formatting?
Why are glibc printf()-functions inconsistent about null pointer formatting?

Time:10-26

With glibc,

  • If your program calls printf("%s", NULL), you get (null), but
  • if your program calls printf("%p", NULL), you get (nil).

But why is this the case?

Note: This is not a question about the C language standard, where passing a null pointer for an "%s" specifier results in undefined behavior; I'm asking about glibc's choices specifically (and these values are hard-coded in the glibc sources).

CodePudding user response:

This is a question for Roland McGrath.

He added vfprintf.c as part of the initial commit of glibc on Feb 17, 1995. This initial version contains both "(nil)" and "(null)" hardcoded for these specific cases. The only comment on this commit is "Initial commit".

https://github.com/lattera/glibc/blob/28f540f45bbacd939bfd07f213bcad2bf730b1bf/stdio/vfprintf.c

For more context, the use of "(null)" for strings was present in FreeBSD 4.4 since at least May 27, 1994, although there is no special strings for the %p format specifier:

https://github.com/freebsd/freebsd-src/commit/58f0484fa251c266ede97b591b499fe3dd4f578e

CodePudding user response:

C standard. 7.1.4

¶1 Each of the following statements applies unless explicitly stated otherwise in the detailed descriptions that follow: If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.

As the C standard does not specify what happens if programmer passes the NULL pointer using %s format specifier, above general rule applies.

IMO it is Undefined Behaviour and there is no inconsistency. Any program passing NULL to the print function using %s is invalid.

  • Related