Background
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. This means that they are not necessarily portable from one system to the next, and additionally multiple conversions may or may not give the desired behavior.Part 1:
Universal Integer/Pointer Storage
It is recommended to use a union if you need to memory to be accessible as both a pointer and an integer rather than make the cast. Since a union is the size of the largest element and will faithfully represent both as the implementation defines, it will ensure the proper behavior and keep data from being lost.
Non-Compliant Code
Code Block | ||
---|---|---|
| ||
unsigned int * ptr = 0xcfcfcfcf; ... unsigned int number = ptr + 1; unsigned int * ptr2 = ptr; |
Compliant
...
Solution
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; |
The non-compliant code leads to many possible conversion errors and additionally overflow. All of these are avoided by using a union. Part 2:
Accessing Memory-Mapped Addresses*
Note: This is a bad idea. The following is a description of how to properly execute a bad idea.
...
The trick here is to convince the compiler you are going to do something bad instead of just assigning a pointer to an integer.
Non-Compliant Code Example
Code Block | ||
---|---|---|
| ||
unsigned int * ptr = 0xcfcfcfcf;
|
Because integers are no longer pointers this could have drastic consequences.
Compliant
...
Solution
Code Block | ||
---|---|---|
| ||
unsigned int * ptr = (unsigned int *) 0xcfcfcfcf; |
...