Function pointer cast to an unrelated type
ID |
c.correctness.function_pointer_cast |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Type Safety |
Language |
C / C++ |
Description
A function pointer is cast to an unrelated type. The C and C++ standards do not guarantee that a function pointer and a data pointer (or an integer) have compatible representations, so this conversion is undefined behavior on platforms where they differ in size or encoding. Keep the value as its function-pointer type, or if interoperating with an API that truly requires this (e.g. dlsym), isolate the cast behind a documented, platform-checked helper.
Rationale
A function pointer is cast to an unrelated type. The C and C++ standards do not guarantee that a function pointer and a data pointer (or an integer) have compatible representations, so this conversion is undefined behavior on platforms where they differ in size or encoding. Keep the value as its function-pointer type, or if interoperating with an API that truly requires this (e.g. dlsym), isolate the cast behind a documented, platform-checked helper.
The following code illustrates the pattern detected by this rule:
typedef int (*handler_t)(int);
void configure(int (*onEvent)(int), void (*onClose)(void), handler_t aliased)
{
// FLAGGED: Function pointer cast to an unrelated type
void *raw = (void *)onEvent;
// FLAGGED: Function pointer cast to an unrelated type
long asInt = (long)onClose;
int (*same)(int) = onEvent;
void *notDetected = (void *)aliased;
int notAPointer = 5;
long alsoNotAPointer = (long)notAPointer;
(void)raw;
(void)asInt;
(void)same;
(void)notDetected;
}
Remediation
Follow secure coding practices and review the references below for detailed remediation guidance.