Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added CS / NCE pair.

...

Noncompliant Code Example

This example is noncompliant on an implementation where pointers are 64 bits and unsigned integers are 32 bits because the result of converting the 64-bit ptr cannot be represented in the 32-bit integer type.

Code Block
bgColor#ffcccc
langc
void f(void) {
  char *ptr;
  /* ... */
  unsigned int number = (unsigned int)ptr;  /* violation */
  /* ... */
}

Compliant Solution

Any valid pointer 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)ptr;  
  /* ... */
}

Noncompliant Code Example

In this noncompliant code example, the pointer ptr is converted to an integer value. Both a pointer and an int are assumed to be 32 bits. The high-order 9 bits of the number are used to hold a flag value, and the result is converted back into a pointer.

...

Please note that this noncompliant code example also violates EXP11-C. Do not make assumptions regarding the layout of structures with bit-fields.

Compliant Solution

Saving a few bits of storage is generally not as important as writing portable code. A struct can be used to provide room for both the pointer and the flag value. This is portable to machines of different word sizes, both smaller and larger than 32 bits, working even when pointers cannot be represented in any integer type.

Code Block
bgColor#ccccff
langc
struct ptrflag {
  char *pointer;
  unsigned int flag :9;
} ptrflag;

char *ptr;
unsigned int flag;
/* ... */
ptrflag.pointer = ptr;
ptrflag.flag = flag;

Noncompliant Code Example

It is sometimes necessary in low-level kernel or graphics code to access memory at a specific location, requiring a literal integer to pointer conversion. In this noncompliant code, a pointer is set directly to an integer constant, where it is unknown whether the result will be as intended.

...

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.

Compliant Solution

Adding an explicit cast may help the compiler convert the integer value into a valid pointer.

...

INT11-EX2: Any valid pointer to void can be converted to intptr_t or uintptr_t and back with no change in value. ( This includes the underlying types if intptr_t and uintptr_t are typedefs, and any typedefs that denote the same types as intptr_t and uintptr_t.)

Code Block
bgColor#ccccff
langc
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);
}

...