While it used to be common practice to use integers and pointers interchangeably in C (although it was not considered good style), the C99 standard has mandated that pointer to integer and integer to pointer conversions are implementation defined. By definition of the standard, the only value which can be considered interchangeable between pointers and integers is the constant 0. This means that less the exception of 0, mixing integers and pointers may have undesired consequences depending on the implementation which is used.
Universal Integer/Pointer Storage
Non-Compliant Code
In this non-compliant code, the pointer ptr
is used in an arithmetic operation that is eventually casted as an integer, as stated above, the actual result for both this assignment and following assignment to ptr2
are implementation defined.
Code Block | |||
---|---|---|---|
| |||
unsigned int myint = 0; unsigned int *ptr = 0xcfcfcfcf&myint; ... unsigned int number = ptr + 1; unsigned int *ptr2 = ptr; |
...
Note: This is a bad idea. The following is a description of how to more properly execute a bad idea.
...
Because integers are no longer pointers this could have drastic consequences.
Compliant Solution
...
Adding in the an explicit cast may help the compiler make a decision thatformat and store the value as expected into the pointer.
Code Block | ||
---|---|---|
| ||
unsigned int * ptr = (unsigned int *) 0xcfcfcfcf;
|
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT14-A | 2 | 2(unlikely) | 3(medium) | P2 | L3 |
References
Wiki Markup |
---|
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 6.3.2.3, "Pointers" |