Versions Compared

Key

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

When performing pointer arithmetic, the size of the computation is automatically scaled to the size of the pointer type. For instance, a pointer to a four-byte integer will be scaled by four bytes at a time.

Improper use of pointer arithmetic can lead to miscalculations that result in subtle and hard to spot coding errors.

Pointer arithmetic in C is a powerful feature when working with many data structures, however it can lead to subtle and hard to spot coding errors.  This is due to the importance of context (the type of the pointer in question) which is likely declared outside the pointer arithmetic expression.  In the case of bounds checking to determine if there is space in a region of memory, this can lead to buffer overflow vulnerabilities.

Background

Pointer arithmetic is based around the concept of scaling computation to the size of the pointer type. When working with arrays this allows for easily accessing elements.

Non-Compliant Code Example

In this example, taken from dowd,

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

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

...

2)

Code Block
bgColor#CCCCFF

int buf[BUF_LEN1024];
int *buf_ptrb = buf;
int i = 0;

while (havedata() && ib < BUF_LENbuf+sizeof(buf))
{
    buf[i]*b++ = parseint(getdata());
    i++;
}

These corrected versions:

...