CERT.ARR.PTR.ARITH
Pointer is used in arithmetic expression
The CERT.ARR.PTR.ARITH checker flags instances of pointers used in arithmetic expressions.
Vulnerability and risk
Pointer arithmetic in C/C++ can be confusing in some scenarios. The expression ptr+1 may be mistakenly interpreted as the addition of 1 to the address held in ptr. In fact, the new memory address depends on the size of bytes of the pointer’s target. This misunderstanding can lead to unexpected behavior if sizeof is applied incorrectly.
Mitigation and prevention
Array indexing by using the array subscript syntax, ptr[expr], is the preferred form of pointer arithmetic because it is often clearer and hence less error-prone than pointer manipulation.
Vulnerable code example
#include <stdint.h>
#include <stddef.h>
void func ( uint8_t *ptr1, uint8_t ptr2[ ] )
{
ptr1 = ptr1 + 5;
ptr1 = ptr1 - 1;
ptr2 = ptr2 + 3;
}
int main()
{
uint8_t a1[ 16 ];
uint8_t a2[ 16 ];
uint8_t data = 0U;
func ( a1, a2 );
return 0;
}
In this non-compliant example, Klocwork reports a CERT.ARR.PTR.ARITH defect on Line 5, 6 and 7 because Pointer is used in arithmetic expressions.