Pointer cast to an integral type
ID |
c.correctness.pointer_to_integral_cast |
Severity |
low |
Remediation Complexity |
hard |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Cast |
Language |
C / C++ |
Description
A pointer is cast to an integral type. The size of a pointer is not guaranteed to match the target integer type, so this conversion can truncate the address on platforms where pointers are wider than the chosen integer, and the resulting value is implementation-defined rather than portable. If the address must be represented as an integer, use intptr_t or uintptr_t from <stdint.h>, which are guaranteed to round-trip through a pointer.
Rationale
A pointer is cast to an integral type. The size of a pointer is not guaranteed to match the target integer type, so this conversion can truncate the address on platforms where pointers are wider than the chosen integer, and the resulting value is implementation-defined rather than portable. If the address must be represented as an integer, use intptr_t or uintptr_t from <stdint.h>, which are guaranteed to round-trip through a pointer.
The following code illustrates the pattern detected by this rule:
void inspect(int *ip, char *cp, void *vp)
{
// FLAGGED: Pointer cast to an integral type
long a = (long)ip;
// FLAGGED: Pointer cast to an integral type
unsigned long b = (unsigned long)cp;
// FLAGGED: Pointer cast to an integral type
int c = (int)vp;
char *d = (char *)cp;
void *e = (void *)vp;
int *f = (int *)vp;
(void)a; (void)b; (void)c; (void)d; (void)e; (void)f;
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.