Pedro Graca <hexkid@dodgeit.com> writes:[color=blue]
> [Jordan's comment on passing an invalid pointer to printf inserted]
>
> Keith Thompson wrote:[color=green]
>> Pedro Graca <hexkid@dodgeit.com> writes:[/color]
>
>[color=green][color=darkred]
>>>Jordan Abel wrote [edited]:
>>>> the act itself of passing an invalid pointer to printf invokes UB.[/color][/color]
>
>[color=green][color=darkred]
>>> What is a valid pointer?[/color][/color]
> [snip examples][color=green][color=darkred]
>>> p = (char*)rand();[/color]
>>
>> 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.
>>[/color]
>
> So the following code does not invoke UB?
>
> char * p;
> p = (char*)rand();
> printf("%c\n", p);[/color]
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.
[color=blue]
> ... and removing the assignment does?
>
> char * p;
> printf("%c\n", p);[/color]
That certainly invokes UB, even with "%p".
--
Keith Thompson (The_Other_Keith)
kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.