Allocation can fail and every successful allocation needs one clear owner and one matching release.
Build a Complete Mental Model
Dynamic allocation requires control of size overflow, allocation failure, initialization, ownership transfer, exactly-one free, and use-after-free. Prefer `sizeof *ptr`, checked size arithmetic, and a single cleanup path.
Apply It in Real C
Allocate a calloc array from a user count and test failure, zero or excessive counts, normal use, and cleanup under AddressSanitizer.
After This Lesson
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count = 5;
int *values = calloc(count, sizeof *values);
if (values == NULL) return EXIT_FAILURE;
for (size_t i = 0; i < count; ++i) values[i] = (int)(i * 10);
for (size_t i = 0; i < count; ++i) printf("%d%c", values[i], i + 1 == count ? '\n' : ' ');
free(values);
values = NULL;
return EXIT_SUCCESS;
}0 10 20 30 40Try It Yourself
Allocate a calloc array from a user count and test failure, zero or excessive counts, normal use, and cleanup under AddressSanitizer.
Memory and Safety Warning
Unchecked allocation, size-multiplication overflow, and using a pointer after free are critical memory defects.
SEI CERT C Coding Standard — Carnegie Mellon SEI