Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A few questions about legal arguments to printf("%s", ...)

I'm creating a modified printf implementation, and I'm not sure about the answers to these questions.

  1. Does zero work as a null string? (Is printf("%s", 0) allowed?)

    I'm guessing no, because 0 is an int. But then this prompts this question:

  2. Does NULL work as a null string? (Is printf("%s", NULL) allowed?)

    Logically, I think it should be yes, because NULL implies a pointer; but a lot of implementations seem to have #define NULL 0, so I feel in practice it might be no. Which is correct?

  3. Does the pointer type have to point to char? (Is printf("%s", (void const *)"") allowed?)

    My guess is that the type doesn't matter, but I'm not sure.

like image 602
user541686 Avatar asked Aug 31 '12 21:08

user541686


1 Answers

Case 1 is undefined behavior because the type of the argument (int) does not match the type required by the format specifier (char *).

Case 2 is undefined behavior for the same reason. NULL is allowed to be defined as any integer constant expression with value 0, or such an expression cast to (void *). None of these types are char *, so the behavior is undefined.

Case 3 is undefined behavior for the same reason. "" yields a valid pointer to a null-terminated character array (string), but when you cast it to const void *, it no longer has the right type to match the format string. Thus the behavior is undefined.

like image 154
R.. GitHub STOP HELPING ICE Avatar answered Sep 18 '22 23:09

R.. GitHub STOP HELPING ICE