Integer value cast directly to a pointer type
ID |
c.correctness.void_pointer_conversion |
Severity |
low |
Remediation Complexity |
hard |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Type Safety |
Language |
C / C++ |
Description
An integer value is cast directly to a pointer type. Unlike converting an existing pointer (e.g. the result of malloc), fabricating a pointer from an arbitrary integer produces an address whose validity the compiler cannot check, and the conversion itself is implementation-defined and non-portable across platforms with different pointer widths. Only do this when the integer is a value the platform genuinely defines as an address (a memory-mapped register, a value from mmap/VirtualAlloc), and document why.
Rationale
An integer value is cast directly to a pointer type. Unlike converting an existing pointer (e.g. the result of malloc), fabricating a pointer from an arbitrary integer produces an address whose validity the compiler cannot check, and the conversion itself is implementation-defined and non-portable across platforms with different pointer widths. Only do this when the integer is a value the platform genuinely defines as an address (a memory-mapped register, a value from mmap/VirtualAlloc), and document why.
The following code illustrates the pattern detected by this rule:
void configure(int handle, unsigned int uhandle, long offset, void *vp, char *cp)
{
// FLAGGED: Integer value cast directly to a pointer type
char *a = (char *)handle;
// FLAGGED: Integer value cast directly to a pointer type
int *b = (int *)uhandle;
// FLAGGED: Integer value cast directly to a pointer type
void *c = (void *)offset;
int *d = (int *)vp;
char *e = (char *)cp;
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.