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.
The only value that can be considered interchangeable between pointers and integers is the constant 0. Except in this case, conversions between integers and pointers can have undesired consequences depending on the implementation. According to the C standard standard, Section 6.3.2.3 [ISO/IEC 9899:2011],
An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
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.
...
Code Block | ||||
---|---|---|---|---|
| ||||
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 non-compliant noncompliant code, a pointer is set directly to an integer constant, where it is unknown whether the result will be as intended.
...
MITRE CWE: CWE-466, "Return of Pointer Value Outside of Expected Rangepointer value outside of expected range"
MITRE CWE: CWE-587, "Assignment of a Fixed Address fixed address to a Pointerpointer"
Bibliography
...