CWARN.BAD.PTR.ARITH

Bad pointer arithmetic

In C and C++, when doing pointer arithmetic, it is possible to accidentally refer to the wrong memory due to the way math operations are implicitly scaled. The CWARN.BAD.PTR.ARITH checker searches for instances in which a pointer has been incremented or decremented by a value that most likely was an oversight of the automatic scaling.

Vulnerability and risk

Bad pointer arithmetic can cause buffer overflow conditions.

Vulnerable code example

1  #define ARRAY_SIZE 5
2  void initialize_array()
3  {
4      int buf[ARRAY_SIZE];
5      for (int* p = buf; p < (buf + ARRAY_SIZE); p += sizeof(int)) {
6          *p = 0;
7      }
8  }

Klocwork produces a bad pointer arithmetic report for line 5 indicating that bad arithmetic is applied to pointer "p". The report here informs the reviewer that the expression p += sizeof(int) is incrementing the pointer ā€œpā€ by sizeof(int) * sizeof(int) bytes (due to automatic scaling) instead of just incrementing it by sizeof(int) bytes. Thus, a buffer overflow occurs in this example.

Fixed code example

1  #define ARRAY_SIZE 5
2  void initialize_array()
3  {
4      int buf[ARRAY_SIZE];
5      for (int* p = buf; p < (buf + ARRAY_SIZE); p++) {
6          *p = 0;
7      }
8  }

The problem from the previous snippet is fixed: the pointer is increment by sizeof(int) bytes instead of sizeof(int) * sizeof(int) bytes.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.