...
Code Block | ||
---|---|---|
| ||
int buf[1024]; int *buf_ptr = buf; while (havedata() && buf_ptr < buf + sizeof(buf)) { *buf_ptr++ = parseint(getdata()); } |
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.
...
Compliant Code Example
1)
Code Block | ||
---|---|---|
| ||
int buf[BUF_LEN]; int *buf_ptr = buf; while (havedata() && buf_ptr < buf[BUF_LEN-1]) { *buf_ptr = parseint(getdata()); buf_ptr++; } |
...