Pointer casting:can the Pointer has value?

73 views Asked by At

can the Pointer have value?? so In which case is it used

int num=100;
int* iptr=NULL;
iptr=reinterpret_cast<int*>(num);
printf("%d \n",num);
printf("%d \n",num);

result 100 100

1

There are 1 answers

0
P.W On
  1. Mappings between pointers and integers are implementation-defined.
  2. Conversion of an integer to a pointer using reinterpret_cast will not be a safely-derived pointer value except under certain conditions. Those conditions are not met in your example.

Citation from CPP draft (N4713):

8.5.1.10 Reinterpret cast
...
6. A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined. [ Note: Except as described in 6.6.4.4.3, the result of such a conversion will not be a safely-derived pointer value. —end note ]

The conditions for Safely-derived pointers.

6.6.4.4.3 Safely-derived pointers
...
2 A pointer value is a safely-derived pointer to a dynamic object only if it has an object pointer type and it is one of the following:
(2.1) — the value returned by a call to the C++ standard library implementation of ::operator new(std::size_t) or ::operator new(std::size_t, std::align_val_t);
(2.2) — the result of taking the address of an object (or one of its subobjects) designated by an lvalue resulting from indirection through a safely-derived pointer value;
(2.3) — the result of well-defined pointer arithmetic using a safely-derived pointer value;
(2.4) — the result of a well-defined pointer conversion of a safely-derived pointer value;
(2.5) — the result of a reinterpret_cast of a safely-derived pointer value;
(2.6) — the result of a reinterpret_cast of an integer representation of a safely-derived pointer value;
(2.7) — the value of an object whose value was copied from a traceable pointer object, where at the time of the copy the source object contained a copy of a safely-derived pointer value.