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

1  #include <stdio.h>
2 
3  void f(void)
4  {
5      if (sizeof(int) == sizeof(float)) {
6          float f = 0.0f;
7          int *ip = (int *)&f;
8          (*ip)++;
9          printf("float is %f\n", f);
10         int i = 0;
11         ip = (int *)&i;
12
13     }
14 }
15 int main(int argc, char *argv[])
16 {
17     f();
18     return 0;
19 }

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

1  #include <stdio.h>
2 
3  void f(void)
4  {
5      if (sizeof(int) == sizeof(float)) {
6          float f = 0.0f;
7          float *ip = &f;
8          (*ip)++;
9          printf("float is %f\n", f);
10         int i = 0;
11
12     }
13 }
14 int main(int argc, char *argv[])
15 {
16     f();
17     return 0;
18 }

In this fixed example, there is no cast between pointers of different object types.

Related checkers

  • MISRA.CAST.OBJ_PTR_TO_PTR.2012