Why is printf literally printing (null) and what exactly is happening?

in a C programming exercise, I am doing something like this (just simplifying):

printf( "%s", 0); 

Output signal

 (null) 

What's going on here? I assume printf interprets null as char * , so up to NULL ? How can I reproduce this result, for example,

 char string[] = NULL; //compiler-error printf( "%s", string); 

?

+5
source share
4 answers

Firstly your

 printf("%s", 0); 

leads to undefined (UB) behavior. %s in printf requires a char * pointer as an argument. You pass 0 , which corresponds to int . This in itself already violates your code, as

 printf("%s", 42); 

will be. For this particular UB, the fact that 0 is zero does not matter.

Secondly, if you really want to try passing the null-ponter format specifier to %s , you should do something like

 printf("%s", (char *) 0); 

Of course, this also leads to undefined behavior, since %s requires a pointer to a valid string as an argument, and (char *) 0 not a valid string pointer. But some implementations prefer to handle such situations gracefully and simply print (null) .

In your particular case, you were just lucky: printf("%s", 0) "worked" just like printf("%s", (char *) 0) , and your implementation saved the day by outputting (null) .

+6
source

As others noted, passing a null pointer to printf %s does not guarantee anything. All things being equal, we expect segmentation violation or other ungrateful failure, because printf trying to dereference a null pointer. However, for convenience, many (most?) printf implementations have an equivalent somewhere deep inside them.

 case 's': char *p = va_arg(argp, char *); if(p == NULL) p = "(null)"; fputs(p, stdout); 
+2
source

You can also do this using something like:

 char *string = NULL; printf("%s", string); 

Many printf() implementations will print (null) or something similar when passing a NULL pointer to %s . But they should not do this (this is not required by the standard).

+1
source

In your example, passing 0 to printf leads to undefined behavior, because the format specifier you specified displays a string, but you gave it an int. To perform replication, you can do the following:

 char *string = NULL; printf("%s", string); 
+1
source

All Articles