Versions Compared

Key

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

While it has been common practice to use integers and pointers interchangeably in C, pointer-to-integer and integer-to-pointer conversions are implementation-defined.

Conversions between integers and pointers can have undesired consequences depending on the implementation. According to the C standardStandard, Section 6.3.2.3 [ISO/IEC 9899:2011],

...

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 also undefined behavior 24 of Annex J.

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.

...

Code Block
bgColor#ccccff
langc
unsigned int *ptr = (unsigned int *) 0xcfcfcfcf;

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.

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.)

...

Tool

Version

Checker

Description

Compass/ROSE   

LDRA tool suite

Include Page
LDRA_V
LDRA_V

94 S

Fully implementedCompass/ROSE  
 PRQA QA-C
Include Page
PRQA_V
PRQA_V
0309 (U)Partially implemented

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

...

TS 17961(Draft) Converting a pointer to integer or integer to pointer [intptrconv]
ISO/IEC TR 24772

...

Pointer casting and pointer type changes

...

...

...

Return of pointer value outside of expected range

...


...

...

...

Assignment of a fixed address to a pointer

Bibliography

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

...

 

...