Versions Compared

Key

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

...

These issues arise because the mapping functions for converting a pointer to an integer or an integer to a pointer must be consistent with the addressing structure of the execution environment.  For example, not all machines have a flat memory model.

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, such as the following:

Code Block

unsigned int *ptr = 0xcfcfcfcf;

These conversions are machine dependent and should be coded only when absolutely necessary.

Noncompliant Code Example

...

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

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

Non-Compliant 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 to conversion. In this non-compliant code, a pointer is set directly to an integer constant, where it is unknown whether the result will be as intended.

Code Block
bgColor#FFcccc

unsigned int *ptr = 0xcfcfcfcf;

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.

Code Block
bgColor#ccccff

unsigned int *ptr = (unsigned int *) 0xcfcfcfcf;

Risk Analysis

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

...