...
In this example, taken from dowd, buf
is an array of 1024 integers and buf_ptr
is used to insert new integers into buf
. If there is data to be inserted into buf
(which is indicated by havedata()
) and buf_ptr
has not been incremented past buf+sizeof(buf)
, then an integer is inserted in buf
via buf_ptr
. However, the sizeof
operator returns the total number of bytes in buf
, which, assuming four-byte integers, is 4096B. This value is then scaled to the size of an integer and added to buf
. As a result, it is possible to write integers past the end of buf
and cause a buffer overflow.
Code Block | ||
---|---|---|
| ||
int buf[1024]; int *buf_ptr = buf; while (havedata() && buf_ptr < buf + sizeof(buf)) { *buf_ptr++ = parseint(getdata()); buf_ptr++; } |
While at first look this code appears correct and that it will prevent overflowing the allocated buffer, in fact buf + sizeof(buf) returns a value corresponding to a region in memory beyond the allocated buffer. This is due to buf
being an int pointer and the result of sizeof(buf) getting multiplied by sizeof(int) accordingly. Thus, this code is vulnerable to buffer overflow.
...
2)
Code Block | ||
---|---|---|
| ||
int buf[1024];
int *b = buf;
while (havedata() && b < buf+sizeof(buf))
{
*b++ = parseint(getdata());
}
|
...