Open In App

Passing NULL to printf in C

Last Updated : 02 Jun, 2017
Comments
Improve
Suggest changes
Like Article
Like
Report
Consider the following C code snippet.
char* p = NULL;
printf("%s", p);
What should be the output of the above program? The print expects a '\0' terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior.

According to Section 7.1.4(of C99 or C11) : Use of library functions

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.

Some compilers may produce null while others Segmentation Fault. GCC prints (null). C
// Effect of passing null pointers to ( %s ) 
// printf in C
#include <stdio.h>

int main()
{
   char* p = NULL;
   printf( "%s", p);
   return 0;
}
Output in GCC:
(null)
Note that the above program may cause undefined behavior as per C standard.  


Next Article
Article Tags :

Similar Reads