CXX.CAST.OBJ_PTR_TO_OBJ_PTR
Cast between a pointer to object type and a pointer to a different object type.
The CXX.CAST.OBJ_PTR_TO_OBJ_PTR checker flags instances where the code casts a pointer to object into a pointer to a different object.
Vulnerability and risk
Casting a pointer to object into a pointer to a different object may result in a pointer that is not correctly aligned, which results in undefined behavior.
Mitigation and prevention
Avoid casting between a pointer to object type and a pointer to a different object type.
Vulnerable code example
Copy
#include <stdio.h>
void f(void)
{
if (sizeof(int) == sizeof(float)) {
float f = 0.0f;
int *ip = (int *)&f;
(*ip)++;
printf("float is %f\n", f);
int i = 0;
ip = (int *)&i;
}
}
int main(int argc, char *argv[])
{
f();
return 0;
}
In this example, Klocwork reports a CXX.CAST.OBJ_PTR_TO_OBJ_PTR defect on Line 7, because accessing an object through a pointer of an incompatible type may result in undefined behavior.
Fixed code example
Copy
#include <stdio.h>
void f(void)
{
if (sizeof(int) == sizeof(float)) {
float f = 0.0f;
float *ip = &f;
(*ip)++;
printf("float is %f\n", f);
int i = 0;
}
}
int main(int argc, char *argv[])
{
f();
return 0;
}
In this fixed example, there is no cast between pointers of different object types.
Related checkers
- MISRA.CAST.OBJ_PTR_TO_PTR.2012