PTR-arith-field
Synopsis
Direct access to a field of a struct, using an offset from the address of the struct.
Enabled by default
Yes
Severity/Certainty
Medium/High

Full description
A field of a struct is accessed directly, using an offset from the address of the struct. Because a struct might in some cases be padded to maintain proper alignment of its fields, it can be very dangerous to access fields using only an offset from the address of the struct itself. This check is identical to MISRAC2004-17.1_a.
Coding standards
- CERT ARR37-C
Do not add or subtract an integer to a pointer to a non-array object
- CWE 188
Reliance on Data/Memory Layout
- MISRA C:2004 17.1
(Required) Pointer arithmetic shall only be applied to pointers that address an array or array element.
Code examples
The following code example fails the check and will give a warning:
struct S{
char c;
int x;
};
void main(void) {
struct S s;
*(&s.c+1) = 10;
}
The following code example passes the check and will not give a warning about this issue:
struct S{
char c;
int x;
};
void example(void) {
struct S s;
s.x = 10;
}