Tuesday, 16 August 2016

Anirudh

Passing NULL to printf() in C

Consider the following code snippet:
char *p = NULL;
printf ("%s", p);
What should be the output of the above code?

The printf() function with "%s" format specifier expects a '\0'-terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf() is undefined behavior in C.

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)" written on the screen while others may give segmentation fault. GCC prints (null).

What is NULL?
NULL is a macro defined by several headers (including stdio.h, stddef.h, stdlib.h, string.h, time.h etc.) as a null pointer constant, typically 0 or ((void *)0). It is a value which is "guaranteed to compare unequal to a pointer to any object or function", as per C standard. That is, a null pointer points definitively nowhere - it is never the address of any object or function. The address-of operator '&' will never yield a null pointer, nor will a successful call to malloc() (malloc does return a null pointer when it fails).

Here is a program to demonstrate the effect of passing null pointer to printf() with different format specifiers.
/* Effects of passing null pointer to printf() */

#include <stdio.h>
int main()
{
    printf ("%s \n", NULL);  // Undefined behavior, prints (null) in GCC
    printf ("%d \n", NULL);  // The value of NULL macro (typically 0)
    printf ("%c \n", NULL);  // The ASCII character corresponding to the value of NULL macro
                             // (generally value is 0, so null character '\0', i.e. blank result).
    return 0;
}

Output in GCC:
(null)
0

Anirudh

About the author →

Anirudh Khanna is a Computer Science student and a geek who firmly believes in the awesomeness of technology! He is a programmer and web designer, also keenly interested in the research of new and innovative ideas in Computer Science.

Subscribe to Geek Factorial via email :