User-Controlled Array Index

User-controlled array index

Description

Using user input as an array index can access memory outside the array's bounds.

Potential impact

  • Information exposure, memory corruption, or crashes

Remediation

Ensure the index is nonnegative and less than the array length.

Examples

Before

c
int idx = atoi(argv[1]);
return values[idx];

After

c
#include <errno.h>
#include <stdlib.h>

char *end = NULL;
errno = 0;
long parsed = strtol(argv[1], &end, 10);
if (errno == ERANGE || end == argv[1] || *end != '\0' ||
    parsed < 0 || (unsigned long)parsed >= VALUE_COUNT) {
    return -1;
}
size_t idx = (size_t)parsed;
return values[idx];

Explanation:

  • Before: External input becomes an index without a bounds check.
  • After: Use strtol to check conversion errors and trailing characters. Reject negative values and values at or above the array length before converting to an index.

References