Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: cleanup

...

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

...

Examples

Code Block
bgColor#CCCCFF
int buf[1024BUF_LEN];
int *buf_ptr = buf;


while (havedata() && buf_ptr < buf + sizeof(buf))[BUF_LEN-1])
{
    *buf_ptr = parseint(getdata());
    buf_ptr++;
}
Code Block
bgColor#CCCCFF

int buf[BUF_LEN];
int *buf_ptr = buf;
int i = 0;

while (havedata() && i < BUF_LEN)
{
    buf[i] = parseint(getdata());
    i++;
}

In this version we explicitly cast buf as a char pointer this serves two goals:these corrected versions:

  1. eliminate It eliminates the coding error of the original code
  2. The maintain clarity of intended result of the expression remains clearwhile reading code

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.

...