Description
Using unvalidated user input as a memory allocation size can cause excessive allocation or a subsequent buffer overflow.
Potential impact
- Denial of service, memory pressure, or memory corruption
Remediation
Check the allowed minimum and maximum sizes, and prevent integer overflow.
Examples
Before
c
size_t n = atoi(argv[1]);
char *buf = malloc(n);
After
c
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#define MAX_ALLOCATION (16U * 1024U * 1024U)
char *end = NULL;
errno = 0;
uintmax_t parsed = strtoumax(argv[1], &end, 10);
if (errno == ERANGE || end == argv[1] || *end != '\0' ||
parsed == 0 || parsed > MAX_ALLOCATION || parsed > SIZE_MAX) {
return;
}
size_t n = (size_t)parsed;
char *buf = malloc(n);
if (buf == NULL) { return; }
Explanation:
- Before: External input directly determines the allocation size.
- After: Use
strtoumaxinstead ofatoito parse the entire string and check conversion errors. Reject zero and values above the application limit orSIZE_MAXbefore converting tosize_tand allocating memory.