Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c89: Convert an int to void* and back

Tags:

c

c89

First off, this is not a dupe of:

Is it safe to cast an int to void pointer and back to int again?

The difference in the questions is this: I'm only using the void* to store the int, but I never actually use it as a void*.

So the question really comes down to this:

Is a void * guaranteed to be at least as wide as an int

I can't use intptr_t because I'm using c89 / ANSI C.

EDIT

In stdint.h from C99 ( gcc version ) I see the following:

/* Types for `void *' pointers.  */
#if __WORDSIZE == 64
# ifndef __intptr_t_defined
typedef long int        intptr_t;
#  define __intptr_t_defined
# endif
typedef unsigned long int   uintptr_t;
#else
# ifndef __intptr_t_defined
typedef int         intptr_t;
#  define __intptr_t_defined
# endif
typedef unsigned int        uintptr_t;
#endif

Could I possibly just jerry rig something similar and expect it to work? It would seem that the casting should work as all intptr_t is is a typedef to an integral type...

like image 431
Robert S. Barnes Avatar asked Aug 12 '11 15:08

Robert S. Barnes


2 Answers

No, this is not guaranteed to be safe.

The C99 standard has this to say (section 6.3.2.3):

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.

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

I'm pretty confident that pre-C99 won't be any different.

like image 109
Oliver Charlesworth Avatar answered Oct 20 '22 13:10

Oliver Charlesworth


There is a C FAQ: Can I temporarily stuff an integer into a pointer, or vice versa? .

The cleanest answer is: no, this is not safe, avoid it and get on with it. But POSIX requires this to be possible. So it is safe on POSIX-compliant systems.

like image 26
cnicutar Avatar answered Oct 20 '22 13:10

cnicutar