While it Although common practice 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 Standard, section subclause 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.
...
Do not convert an integer type to a pointer type if the resulting pointer is incorrectly aligned, does not point to an entity of the referenced type, or is a trap representation.
Do not convert a pointer type to an integer type if the result cannot be represented in the integer type.
...
Code Block | ||||
---|---|---|---|---|
| ||||
void f(void) { char *ptr; /* ... */ unsigned int number = (unsigned int)ptr; /* violationViolation */ /* ... */ } |
Compliant Solution
...
A similar scheme was used in early versions of Emacs, limiting its portability and preventing the ability to edit files larger than 8MB.
Please note Note that this noncompliant code example also violates EXP11-C. Do not make assumptions regarding the layout of structures with bit-fields.
...
INT11-EX2: Any valid pointer to void
can be converted to intptr_t
or uintptr_t
and back with no change in value. This exception includes the underlying types if intptr_t
and uintptr_t
are typedef
s, and any typedef
s that denote the same types as intptr_t
and uintptr_t
.
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE | |||||||||
Coverity | 6.5 | POINTER_CONVERSION_LOSES_BITS | Fully Implemented | ||||||
| 94 S | Fully implemented | |||||||
PRQA QA-C |
| 0309 (U) | Partially implemented |
...
CERT C++ Secure Coding Standard | INT11-CPP. Take care when converting from pointer to integer or integer to pointer |
ISO/IEC TR 24772:2013 | Pointer Casting and Pointer Type Changes [HFC] |
ISO/IEC TS 17961 (Draft) | Converting a pointer to integer or integer to pointer [intptrconv] |
MITRE CWE | CWE-466, Return of pointer value outside of expected range CWE-587, Assignment of a fixed address to a pointer |
Bibliography
[ISO/IEC 9899:2011] | Section 6.3.2.3, "Pointers" |
...