The byte count you pass to malloc is usually a product: count * sizeof *pointer. If count comes from input or keeps growing, that product can exceed SIZE_MAX. Unsigned multiplication does not fail; it wraps around to a small number. malloc then happily returns a small block, the code writes count elements into it, and every write past the block's end corrupts the heap. This exact pattern has caused many real security vulnerabilities. The defense is a check that runs before the multiplication, so the wrapped number is never computed.
Predict and run
Read the program before pressing Run. Write down its output and explain why the check cannot overflow.
#include <stdio.h>
#include <stdint.h>
int main(void) {
size_t count = 4;
if (count <= SIZE_MAX / sizeof(int)) {
puts("Fits");
}
return 0;
}Check your prediction
FitsSIZE_MAX / sizeof(int) is the largest element count whose byte count still fits in a size_t. Four is far below it. Division can only make a number smaller, so the check never overflows itself. Change count to SIZE_MAX and the message disappears, without any overflowing multiplication having run.
Watch a product wrap
This program computes a byte count the unsafe way, only to print it. It does not allocate anything:
#include <stdio.h>
#include <stdint.h>
int main(void) {
size_t count = SIZE_MAX / 2 + 2;
size_t bytes = count * 2;
printf("requested elements: more than half of SIZE_MAX\n");
printf("computed bytes: %zu\n", bytes);
return 0;
}requested elements: more than half of SIZE_MAX
computed bytes: 2The true product is SIZE_MAX + 3, which wraps around to 2. A program that passed 2 to malloc and then wrote "more than half of SIZE_MAX" two-byte elements would be writing far beyond its block. Unsigned wrap is defined behavior, so no default sanitizer reports the multiplication. (Clang's opt-in -fsanitize=unsigned-integer-overflow can, but it also flags deliberate wraps.) Only your check can.
One helper for every byte count
Put the check in one function and use it everywhere. It takes the element size as a parameter, so it works for any type:
int checked_bytes(size_t count, size_t size, size_t *out) {
if (size != 0 && count > SIZE_MAX / size) { return 0; }
*out = count * size;
return 1;
}The size != 0 test avoids dividing by zero. Like Day 1's functions, it commits to *out only on success.
calloc checks the product for you
calloc(count, size) takes the two factors separately and must return NULL if their product cannot be allocated, so mainstream C libraries check for overflow inside it. It also sets every byte to zero. That is convenient for an array of counters, but "all bytes zero" is not the same as "a valid record". A zeroed analyzer Record has an empty topic and 0 minutes, which the input contract rejects. Treat zeroed storage as reserved space until your code writes a real value into it.
Decide what an empty request means
What should malloc(0) return? The standard lets each implementation choose: either NULL, or a unique pointer that must not be dereferenced but must still be freed. Code that receives NULL then cannot tell "no memory" from "nothing requested". This course removes the ambiguity with a policy: an empty collection has NULL data, length 0 and capacity 0, and the code never asks for zero bytes. A request for zero elements is reported as its own outcome, not passed to the allocator.
Practice
Your turn
Write Status checked_bytes(size_t count, size_t size, size_t *out) with three outcomes: STATUS_EMPTY when count or size is 0, STATUS_TOO_LARGE when the product would exceed SIZE_MAX, otherwise STATUS_OK with the product stored in *out. Failures leave *out unchanged. The starter must print 3 x 8: ok, bytes 24, 0 x 8: empty, bytes 24, 5 x 0: empty, bytes 24, huge x 8: too large, bytes 24, max fit x 8: ok.
#include <stdio.h>
#include <stdint.h>
typedef enum { STATUS_OK, STATUS_EMPTY, STATUS_TOO_LARGE } Status;
const char *status_name(Status status) {
switch (status) {
case STATUS_OK: return "ok";
case STATUS_EMPTY: return "empty";
case STATUS_TOO_LARGE: return "too large";
}
return "unknown";
}
/* Write checked_bytes here. */
int main(void) {
size_t bytes = 0;
Status s = checked_bytes(3, 8, &bytes);
printf("3 x 8: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(0, 8, &bytes);
printf("0 x 8: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(5, 0, &bytes);
printf("5 x 0: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(SIZE_MAX / 8 + 1, 8, &bytes);
printf("huge x 8: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(SIZE_MAX / 8, 8, &bytes);
printf("max fit x 8: %s\n", status_name(s));
return 0;
}Hint 1: the idea
SIZE_MAX / 8 is the largest count that fits and SIZE_MAX / 8 + 1 is the smallest that does not. Testing both sides of the boundary proves the comparison uses > and not >=.
Hint 2: a first step
Write the empty case first and run: the two empty lines should be right. Then ask which values you are allowed to divide by at that point in the function, and turn "count * size is bigger than SIZE_MAX" into a comparison that never multiplies.
Show one solution
#include <stdio.h>
#include <stdint.h>
typedef enum { STATUS_OK, STATUS_EMPTY, STATUS_TOO_LARGE } Status;
const char *status_name(Status status) {
switch (status) {
case STATUS_OK: return "ok";
case STATUS_EMPTY: return "empty";
case STATUS_TOO_LARGE: return "too large";
}
return "unknown";
}
Status checked_bytes(size_t count, size_t size, size_t *out) {
if (count == 0 || size == 0) { return STATUS_EMPTY; }
if (count > SIZE_MAX / size) { return STATUS_TOO_LARGE; }
*out = count * size;
return STATUS_OK;
}
int main(void) {
size_t bytes = 0;
Status s = checked_bytes(3, 8, &bytes);
printf("3 x 8: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(0, 8, &bytes);
printf("0 x 8: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(5, 0, &bytes);
printf("5 x 0: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(SIZE_MAX / 8 + 1, 8, &bytes);
printf("huge x 8: %s, bytes %zu\n", status_name(s), bytes);
s = checked_bytes(SIZE_MAX / 8, 8, &bytes);
printf("max fit x 8: %s\n", status_name(s));
return 0;
}3 x 8: ok, bytes 24
0 x 8: empty, bytes 24
5 x 0: empty, bytes 24
huge x 8: too large, bytes 24
max fit x 8: okThe empty check runs first, which also guarantees the division never divides by zero. The two boundary calls show the comparison is exact: one count past the limit is refused, the limit itself is accepted. The last call does not print the product because it depends on the platform's SIZE_MAX. Next, you will decide who is responsible for freeing a block once it exists.
Completion is saved in this browser only. It does not measure mastery.