cybersecurity · beginner · ~15 min · safe pentest lab

Allocation size multiplication guard

Detect and prevent unsigned integer multiplication overflow before memory allocation.

Challenge

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.

Your Task

Implement:

int safe_calc_alloc_size(size_t count, size_t elem_size, size_t *out_size);

Calculate count * elem_size safely.

Rules

  1. If out_size == NULL, return -1.
  2. If count * elem_size would overflow size_t, return -1 without modifying *out_size.
  3. Otherwise, set *out_size = count * elem_size and return 0.

Example

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

Input format

count: element count; elem_size: byte size per element; out_size: pointer to store result.

Output format

Returns 0 on success, -1 on overflow or NULL pointer.

Constraints

Freestanding logic. Handle count == 0 and elem_size == 0 safely.

Starter code

#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;
}

Common mistakes

Checking overflow after the multiplication wraps around; division by zero when count == 0.

Edge cases to handle

count == 0 or elem_size == 0 returns 0 with *out_size = 0; SIZE_MAX exact product; NULL out_size returns -1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.