While it used to be has been common practice to use integers and pointers interchangeably in C (although it was not considered good style), the C99 standard has mandated clearly indicates that pointer to integer and integer to pointer conversions are implementation-defined.
Wiki Markup |
---|
According to C99 \[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\], the only value which can be considered interchangeable between pointers and integers is the constant 0. ThisExcept meansin thatthis lesscase, the exception of 0, mixing conversions between integers and pointers may have undesired consequences depending on the implementation which is used: |
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.
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
unsigned int *ptr = (unsigned int *)0xcfcfcfcf; |
Risk Analysis
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT14 INT15-A | 2 1 (low) | 2 (unlikelyprobable) | 31 (mediumhigh) | P2 | L3 |
References
Wiki Markup |
---|
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 6.3.2.3, "Pointers" |