...
Code Block | ||||
---|---|---|---|---|
| ||||
int buf[INTBUFSIZE];
int *buf_ptr = buf;
while (havedata() && buf_ptr < (buf + sizeof(buf))) {
*buf_ptr++ = parseint(getdata());
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
int buf[INTBUFSIZE];
int *buf_ptr = buf;
while (havedata() && buf_ptr < (buf + INTBUFSIZE)) {
*buf_ptr++ = parseint(getdata());
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
int buf[INTBUFSIZE];
int *buf_ptr = buf;
while (havedata() && buf_ptr < &buf[INTBUFSIZE] {
*buf_ptr++ = parseint(getdata());
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct big {
unsigned long long ull_1; /* typically 8 bytes */
unsigned long long ull_2; /* typically 8 bytes */
unsigned long long ull_3; /* typically 8 bytes */
int si_4; /* typically 4 bytes */
int si_5; /* typically 4 bytes */
};
/* ... */
size_t skip = offsetof(struct big, ull_2);
struct big *s = (struct big *)malloc(sizeof(struct big));
if (!s) {
/* Handle malloc() error */
}
memset(s + skip, 0, sizeof(struct big) - skip);
/* ... */
free(s);
s = NULL;
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct big {
unsigned long long ull_1; /* typically 8 bytes */
unsigned long long ull_2; /* typically 8 bytes */
unsigned long long ull_3; /* typically 8 bytes */
int si_4; /* typically 4 bytes */
int si_5; /* typically 4 bytes */
};
/* ... */
size_t skip = offsetof(struct big, ull_2);
struct big *s = (struct big *)malloc(sizeof(struct big));
if (!s) {
/* Handle malloc() error */
}
memset((char *)s + skip, 0, sizeof(struct big) - skip);
/* ... */
free(s);
s = NULL;
|
...
How long is 4 yards plus 3 feet? It is obvious from elementary arithmetic that any answer involving ' 7 ' is wrong, as the student did not take the units into account. The right method is to convert both numbers to reflect the same units.
...
ROSE can catch both NCE's by searching for pointer arithmetic expressions involving different units. The '"different units' " is the tricky part, but you can try to identify an expression's units using some simple heuristics:
- A pointer to a '
foo
' object has 'foo
' as the unit. - A pointer to
char *
has the unit ' byte'. - Any
sizeof
oroffsetof
expression also has the unit ' byte'. - Any variable used in an index to an array of
foo
objects (eg e.g.,foo[variable]
) has 'foo
' as the unit.
In addition to pointer arithmetic expressions, one can also hunt for array index expressions, as array[index]
is merely shorthand for '"array + index
'."
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: EXP08-CPP. Ensure pointer arithmetic is used correctly
ISO/IEC TR 17961 (Draft) Adding or subtracting a byte count to an element pointer [cntradd]
ISO/IEC PDTR 24772 "HFC Pointer casting and pointer type changes" and "RVG Pointer Arithmetic"
...