Why does printing a null char (‘\0’, 0) with %s prints the “(null)” string actually?
Like this code:
char null_byte = '\0';
printf("null_byte: %s\n", null_byte);
…printing:
null_byte: (null)
…and it even runs without errors under Valgrind, all I get is the compiler warning warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat] (note: I’m using gcc 4.6.3 on 32bit Ubuntu)
It’s undefined behavior, but it happens that on your implementation:
intvalue of 0 that you pass is read by%sas a null pointer%sbyprintfhas special-case code to identify a null pointer and print(null).Neither of those is required by the standard. The part that is required[*], is that a
charused in varargs is passed as anint.[*] Well, it’s required given that on your implementation all values of
charcan be represented asint. If you were on some funny implementation wherecharis unsigned and the same width asint, it would be passed asunsigned int. I think that funny implementation would conform to the standard.