Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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.

See undefined behavior 24.

Do not convert an integer type to a pointer type if the resulting pointer is incorrectly aligned, does not point to an entity of the referenced type, or is a trap representation.

Do not convert a pointer type to an integer type if the result cannot be represented in the integer type (see undefined behavior 24).

The mapping between pointers and integers must be consistent with the addressing structure of the execution environment. Issues may arise, for example, on architectures that have a segmented memory model.

...

Code Block
bgColor#ccccff
langc
unsigned int *g(void) {
  volatile uintptr_t iptr = 0xdeadbeef;
  unsigned int *ptr = (unsigned int *)iptr;
  /* ... */
  return ptr;
}

The volatile qualifier typically prevents the compiler from diagnosing the assignment of an integer to a pointer.

Exceptions

INT36-EX1: A null pointer can be converted to an integer; it takes on the value 0. Likewise, a the integer value 0 integer can be converted to a pointer; it becomes the null pointer.

...

Code Block
bgColor#ccccff
langc
#include <assert.h>
#include <stdint.h>
 
void h(void) {
  intptr_t i = (intptr_t)(void *)&i;
  uintptr_t j = (uintptr_t)(void *)&j;
 
  void *ip = (void *)i;
  void *jp = (void *)j;
 
  assert(ip == &i);
  assert(jp == &j);
}

...

Converting from pointer to integer or vice versa results in unportable code that is not portable and may create unexpected pointers to invalid memory locations.

...

CERT C++ Secure Coding StandardINT11-CPP. Take care when converting from pointer to integer or integer to pointer
ISO/IEC TR 24772:2013Pointer Casting and Pointer Type Changes [HFC]
ISO/IEC TS 17961:2013Converting a pointer to integer or integer to pointer [intptrconv]
MITRE CWECWE-466, Return of pointer value outside of expected rangePointer Value Outside of Expected Range
CWE-587, Assignment of a fixed address Fixed Address to a pointerPointer

Bibliography

[ISO/IEC 9899:2011]Subclause 6.3.2.3, "Pointers"

 

...