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.
Conversions between integers and pointers can have undesired consequences depending on the implementation. According to the C Standard, Section 6.3.2.3 [ISO/IEC 9899:2011],
...
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.
See also undefined behavior 24 of Annex J.
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.
These issues arise because the mapping functions for converting a pointer to an integer or an integer to a pointer must be consistent with the addressing structure of the execution environment. For example, not all machines have a flat memory model.
...
Please note that this noncompliant code example also violates EXP11-C. Do not make assumptions regarding the layout of structures with bit-fields.
Compliant Solution
Saving a few bits of storage is generally not as important as writing portable code. A struct
can be used to provide room for both the pointer and the flag value. This is portable to machines of different word sizes, both smaller and larger than 32 bits, working even when pointers cannot be represented in any integer type.
...
CERT C++ Secure Coding Standard | INT11-CPP. Take care when converting from pointer to integer or integer to pointer |
---|---|
ISO/IEC TS 17961 | (Draft) Converting a pointer to integer or integer to pointer [intptrconv] |
ISO/IEC TR 24772 | Pointer casting and pointer type changes [HFC] |
MITRE CWE | CWE-466, Return of pointer value outside of expected range CWE-587, Assignment of a fixed address to a pointer |
...