C Programming • C17 baseline, standards-specific features labeled
Dynamic Memory with malloc and free
Allocate only when needed, check allocation results, and release each owned allocation exactly once.
malloc requests a block of bytes and returns a pointer to the start, or a null pointer if allocation fails. sizeof *pointer keeps the requested element size tied to the pointed-to type. Keep ownership clear: every successful allocation needs a matching free.
Example
#include <stdlib.h>
#include <stdint.h>
int make_values(size_t count, int **result) {
if (result == NULL) {
return 0;
}
if (count > SIZE_MAX / sizeof **result) {
return 0;
}
int *values = malloc(count * sizeof *values);
if (values == NULL && count != 0) {
return 0;
}
*result = values;
return 1;
}
What to expect
On success, the caller owns the returned allocation and must call free on it, including when count is zero and the result is null.
Key idea: Define ownership and failure behavior in the function contract; do not use a pointer after freeing its storage.