Re: casting unsigned int to void*
On 07/30/2012 01:33 PM, Fred K wrote:
> The Xpm pixmap library contains code that casts an unsigned int
> to a (void *), passing that as an argument to a function
> that expects a (void *):
>
> /* Function prototype: */
> xpmHashIntern (xpmHashTable *table, char *tag, void *data));
>
> /* Calling it, casting 3rd argument: */
> int a = <something>;
> xpmHashIntern(hashtable, color->string, (void *)a );
>
> On a 64-bit platform where pointers are 64 bits and ints
> are 32 bits, is this safe?
The fact that pointers are 64 bits and ints are 32 bits makes it more
difficult for this to work, but not impossible. On a platform where both
are the same size, it's more likely to work, but that's still not
guaranteed. The precise requirements are as follows:
Converting an integer constant expression with a value of 0 to void* is
guaranteed by the standard to result in a null pointer value.
Converting a pointer to void into either intptr_t or uintptr_t produces
a value that can be converted back to void*, resulting in a pointer that
is equivalent to the original pointer. Those two types are optional; if
supported, they are defined in <stdint.h>, which was introduced in C99.
You can check whether they are supported by checking whether INTPTR_MAX
or UINTPTR_MAX are #defined.
In all other cases, while converting an integer value to a pointer is
permitted, "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."
Whether or not this code works correctly is therefore
implementation-specific. It would never have been written and released
unless it actually did work, somewhere, but that's no guarantee that it
will work anywhere else.
|