Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it safe to cast pointer to int and later back to pointer again?

Tags:

c++

pointers

Is it safe to cast pointer to int and later back to pointer again?

How about if we know if the pointer is 32 bit long and int is 32 bit long?

long* juggle(long* p) {     static_assert(sizeof(long*) == sizeof(int));     int v = reinterpret_cast<int>(p); // or if sizeof(*)==8 choose long here     do_some_math(v); // prevent compiler from optimizing     return reinterpret_cast<long*>(v); }  int main() {     long* stuff = new long(42);     long* ffuts = juggle(stuff);      std::cout << "Is this always 42? " << *ffuts << std::endl; } 

Is this covered by the Standard?

like image 362
hasdf Avatar asked Aug 25 '10 16:08

hasdf


People also ask

What happens when you cast a pointer to an int?

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.

Does casting a pointer change its value?

A cast does not change the value of an object. While technically correct, your answer is misleading. Casting a pointer to a class instance may return a different pointer address than the casted pointer contains.

What happens when you cast a pointer?

A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

Can you assign a pointer to an int?

No, it is no valid to assign a pointer to an integer. It's a constraint violation of the assignment operator (C99, 6.5. 16.1p1).


1 Answers

No.

For instance, on x86-64, a pointer is 64-bit long, but int is only 32-bit long. Casting a pointer to int and back again makes the upper 32-bit of the pointer value lost.

You may use the intptr_t type in <cstdint> if you want an integer type which is guaranteed to be as long as the pointer. You could safely reinterpret_cast from a pointer to an intptr_t and back.

like image 65
kennytm Avatar answered Oct 17 '22 18:10

kennytm