Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changes based on expert reviews

...

Compliant Solution

Any valid pointer to void can be converted to intptr_t or uintptr_t and back with no change in value (see INT11-EX2).

Code Block
bgColor#ccccff
langc
void f(void) {
  char *ptr;
  /* ... */
  uintptr_t number = (uintptr_t)(void *)ptr;  
  /* ... */
}

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
langc
unsigned int *g(void) {
  unsigned int *ptr = 0xcfcfcfcf;
 0xdeadbeef;
  /* ... */
  return ptr;
} 

The result of this assignment is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

...

Adding an explicit cast may help the compiler convert the integer value into a valid pointer. A common technique is to assign the integer to a volatile-qualified object of type intptr_t or uintptr_t and then assign the integer value to the pointer. 

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

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

Exceptions

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

...