Versions Compared

Key

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

...

This is because the mapping functions for converting a pointer to an integer or an integer to a pointer are intended to
be consistent with the addressing structure of the execution environment.

Non-Compliant Code Example

In this non-compliant code example, the pointer ptr is used in an arithmetic operation that is eventually converted to an integer value. As previously stated, the result of this assignment and following assignment to ptr2 are implementation defined.

Code Block
bgColor#ffcccc
unsigned int myint = 0;
unsigned int *ptr = &myint;
/* ... */
unsigned int number = ptr + 1;
unsigned int *ptr2 = ptr;

Compliant Solution

A union can be used to give raw memory access to both an integer and a pointer. This is an efficient approach as the structure only requires as much storage as the larger of the two fields.

Code Block
bgColor#ccccff
union intpoint {
  unsigned int *pointer;
  unsigned int number;
} intpoint;
/* ... */
intpoint mydata = 0xcfcfcfcf;
/* ... */
unsigned int num = mydata.number + 1;
unsigned int *ptr = mydata.pointer;

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.

...

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.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

INT15-A

1 (low)

2 (probable)

1 (high)

P2

L3

References

Wiki Markup
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 6.3.2.3, "Pointers"