PTR-arith-var
Synopsis
Invalid pointer arithmetic with an automatic variable that is neither an array nor a pointer.
Enabled by default
Yes
Severity/Certainty
Medium/High

Full description
The address of an automatic variable is taken, and arithmetic is performed on it. This should be avoided, because memory beyond the memory that was allocated for an automatic variable is invalid, and attempting to access it can lead to an application crash. This check handles local variables, parameters and globals, including structs. This check is identical to MISRAC2004-17.1_c, MISRAC++2008-5-0-16_b.
Coding standards
- CWE 120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
- MISRA C:2004 17.1
(Required) Pointer arithmetic shall only be applied to pointers that address an array or array element.
- MISRA C++ 2008 5-0-16
(Required) A pointer operand and any pointer resulting from pointer arithmetic using that operand shall both address elements of the same array.
Code examples
The following code example fails the check and will give a warning:
void example(int x) {
*(&x+10) = 5;
}
The following code example passes the check and will not give a warning about this issue:
void example(int *x) {
*(x+10) = 5;
}