CERT-ARR39-C
In this section:
Synopsis
Do not add or subtract a scaled integer to a pointer.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
When performing pointer arithmetic, the size of the value to add to or subtract from a pointer is automatically scaled to the size of the type of the referenced array object. Adding or subtracting a scaled integer value to or from a pointer is invalid because it may yield a pointer that does not point to an element within or one past the end of the array.
Coding standards
- CERT ARR39-C
Do not add or subtract a scaled integer to a pointer
- CWE 468
Incorrect Pointer Scaling
Code examples
The following code example fails the check and will give a warning:
enum { INTBUFSIZE = 80 };
extern int getdata(void);
int buf[INTBUFSIZE];
void func(void) {
int *buf_ptr = buf;
while (buf_ptr < (buf + sizeof(buf))) {
*buf_ptr++ = getdata();
}
}
The following code example passes the check and will not give a warning about this issue:
enum { INTBUFSIZE = 80 };
extern int getdata(void);
int buf[INTBUFSIZE];
void func(void) {
int *buf_ptr = buf;
while (buf_ptr < (buf + INTBUFSIZE)) {
*buf_ptr++ = getdata();
}
}