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
#define ARRAY_SIZE 5
void initialize_array()
{
int buf[ARRAY_SIZE];
for (int* p = buf; p < (buf + ARRAY_SIZE); p += sizeof(int)) {
*p = 0;
}
}
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
#define ARRAY_SIZE 5
void initialize_array()
{
int buf[ARRAY_SIZE];
for (int* p = buf; p < (buf + ARRAY_SIZE); p++) {
*p = 0;
}
}
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
External guidance
Security training
Application security training materials provided by Secure Code Warrior.