Good Code
The good version checks that count * sizeof **out fits in size_t before allocating. The output pointer is written only after the size is proven.
Lesson 08
Check multiplication before allocating arrays so a wrapped byte count does not create a too-small buffer.
#include <stdint.h>
#include <stdlib.h>
int allocate_scores(size_t count, int **out)
{
// Check multiplication before asking malloc for bytes.
if (out == NULL || count > SIZE_MAX / sizeof **out) {
return -1;
}
*out = malloc(count * sizeof **out);
return *out == NULL ? -1 : 0;
}#include <stdlib.h>
int *allocate_scores(size_t count)
{
// Overflow can make malloc reserve fewer bytes than requested.
return malloc(count * sizeof(int));
}The good version checks that count * sizeof **out fits in size_t before allocating. The output pointer is written only after the size is proven.
The bad version multiplies directly inside malloc. If the multiplication wraps, the loop that fills the array can write past the smaller allocation.
malloc, because overflow can turn a large request into a small allocation.