Pedro Graca said:
[Jordan's comment on passing an invalid pointer to printf inserted]
Keith said:
Jordan Abel wrote [edited]:
the act itself of passing an invalid pointer to printf invokes UB.
What is a valid pointer? [snip examples]
p = (char*)rand();
This is legal, but the result of converting an int value to char* is
implementation-defined (except for the special case of a null pointer
constant). The value of p may or may not be valid.
So the following code does not invoke UB?
char * p;
p = (char*)rand();
printf("%c\n", p);
You need "%p", not "%c". Actually, the "%p" format expects a void*;
you can almost certainly get away with passing a char* instead, but
IMHO it's better style to convert it:
printf("%p\n", (void*)p);
C99 6.3.2.3p5:
An integer may be converted to any pointer type. Except as
previously specified, the result is implementation-defined, might
not be correctly aligned, might not point to an entity of the
referenced type, and might be a trap representation.
The "previously specified" part refers to null pointer constants.
Alignment shouldn't be an issue for char*, but you could still get a
trap representation. If so, evaluating p, whether you then pass the
value to printf() or not, invokes undefined behavior.
... and removing the assignment does?
char * p;
printf("%c\n", p);
That certainly invokes UB, even with "%p".