cybersecurity · beginner · ~15 min · safe pentest lab
Detect and prevent unsigned integer multiplication overflow before memory allocation.
When allocating an array in C via malloc(count * sizeof(element)), integer multiplication can wrap around SIZE_MAX. A tiny buffer is allocated, leading to immediate heap buffer overflow when the elements are written.
Implement:
int safe_calc_alloc_size(size_t count, size_t elem_size, size_t *out_size);
Calculate count * elem_size safely.
out_size == NULL, return -1.count * elem_size would overflow size_t, return -1 without modifying *out_size.*out_size = count * elem_size and return 0.size_t total = 0;
safe_calc_alloc_size(10, 4, &total); // returns 0, total = 40
safe_calc_alloc_size(SIZE_MAX / 2, 4, &total); // returns -1, overflow detected
count: element count; elem_size: byte size per element; out_size: pointer to store result.
Returns 0 on success, -1 on overflow or NULL pointer.
Freestanding logic. Handle count == 0 and elem_size == 0 safely.
#include <stddef.h>
#include <stdint.h>
/* Calculate count * elem_size safely. If overflow occurs or out_size is NULL,
return -1 without modifying *out_size. On success, store product in *out_size and return 0. */
int safe_calc_alloc_size(size_t count, size_t elem_size, size_t *out_size) {
(void)count; (void)elem_size; (void)out_size;
return -1;
}
Checking overflow after the multiplication wraps around; division by zero when count == 0.
count == 0 or elem_size == 0 returns 0 with *out_size = 0; SIZE_MAX exact product; NULL out_size returns -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.