# ABV.ITERATOR

## Buffer overflow-array index out of bounds in an iteration

ABV.ITERATOR checks for out-of-bounds access to an array element using a pointer in an iteration through the array. The checker flags any code in which a buffer overflow could occur as a result of this situation.

## Vulnerability and risk

Consequences of buffer overflow include valid data being overwritten and execution of arbitrary and potentially malicious code.

## Vulnerable code example 1

Copy
```1
2
3
4
5
6
7
8
9
10
11
`   int example1()   {       int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};       int *p;       for (p = a ; p < a + 10; p++)       {           if (bar(*p) < 5)               break;       }       return *p;   // ABV.ITERATOR   }````

Klocwork produces a buffer overflow report for line 10 indicating that pointer 'p' is used when its value may exceed the bounds of array 'a'. Pointer 'p' is assigned to 'a' and iterated at line 5. In this case, the iteration may cause array 'a' to overrun its limit of 10.

## Fixed code example 1

Copy
```1
2
3
4
5
6
7
8
9
10
11
12
13
`   int example1()   {       int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};       int *p;       for (p = a ; p < a + 10; p++)       {           if (bar(*p) < 5)               break;       }      if (p < a + 10)        return *p;      return 0;   }````

In the fixed code example, a check is made at line 10 to ensure that array 'a' can't overflow.

## Vulnerable code example 2

Copy
```1
2
3
4
5
6
7
8
9
`   int example2(int x)   {       int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};       int *p = bar (a, x); //function returns a pointer to some element in "a"       if (p < a + 5)            return *p;          return p[5]; // DEFECT: p[5] points to a[11] or beyond    }````

Klocwork produces an ABV.ITERATOR report at line 8, indicating that array 'a' will overflow after the iteration.

## Fixed code example 2

Copy
```1
2
3
4
5
6
7
8
9
`   int example2(int x)   {       int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};       int *p = bar (a, x); //function returns a pointer to some element in "a"       if (p >= a + 5)            return *p;          return p[5];     }````

In the fixed code example, the syntax is corrected in line 5, and the buffer overflow is avoided.

## Security training

Application security training materials provided by Secure Code Warrior.

## Extension

This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.