Description
Passing an unchecked byte count to malloc can request excessive memory. A conversion or calculation error can also leave the buffer too small.
Potential impact
A large request can exhaust memory. Writing the intended amount to an undersized buffer can corrupt memory.
Remediation
Parse the entire input and verify the allowed range before converting to size_t. If you calculate the byte count from that value, check the arithmetic for overflow as well.
Examples
Both excerpts read argv[1]. Check argc > 1 before parsing so the argument is present.
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; }
The example checks strtoumax for conversion errors and trailing characters. It allows parsed sizes from 1 byte through 16 MiB that fit within SIZE_MAX and handles malloc failure.