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).
Output in GCC:
Note that the above program may cause undefined behavior as per C standard.
This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Nested printf (printf inside printf) in C
- Passing by pointer Vs Passing by Reference in C++
- How to print % using printf()?
- Return values of printf() and scanf() in C/C++
- What is use of %n in printf() ?
- How to change the output of printf() in main() ?
- Cin-Cout vs Scanf-Printf
- Execution of printf with ++ operators
- What is the difference between printf, sprintf and fprintf?
- Use of & in scanf() but not in printf()
- puts() vs printf() for printing a string
- Dangling, Void , Null and Wild Pointers
- NULL pointer in C
- What is a Pointer to a Null pointer
- NULL undeclared error in C/C++ and how to resolve it
- Parameter Passing Techniques in C/C++
- Passing Reference to a Pointer in C++