...
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 3 times further past the end of the buffer, thus allowing overflow.
Compliant Code Example
Code Block | ||
---|---|---|
| ||
int buf[1024]; int *buf_ptr = buf; while (havedata() && buf_ptr < (char *)buf + sizeof(buf)) { *buf_ptr = parseint(getdata()); buf_ptr++; } |
...
- It eliminates the coding error of the original code
- The intended result of the expression remains clear
Risk Analysis
Failure to notice a coding error of this variety would easily become a buffer overflow vulnerability. In a worst case scenario this could lead to arbitrary code execution and thus hold severe risk.