Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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
bgColor#CCCCFF
int buf[1024];
int *buf_ptr = buf;

while (havedata() && buf_ptr < (char *)buf + sizeof(buf))
{
    *buf_ptr = parseint(getdata());
    buf_ptr++;
}

...

  1. It eliminates the coding error of the original code
  2. 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.

Reference