Ask for memory, own the cleanup
Allocate runtime-sized objects and arrays with malloc, calloc, realloc, and free while preserving ownership.
After this lesson
You should be able to
- Allocate an array with overflow-aware size calculation and check failure.
- Use realloc without losing the original allocation on failure.
Lifetime chosen at runtime
Dynamic allocation is useful when size or lifetime is not known at compile time. malloc reserves uninitialized storage, calloc reserves and zero-initializes bytes, and both return null on failure. In C, do not cast malloc's return; include stdlib.h.
Check count * sizeof element for overflow before allocation when count is untrusted. Use sizeof *pointer so the allocation remains correct if the pointed-to type changes.
if (count > SIZE_MAX / sizeof *values) {
fprintf(stderr, "Requested array is too large\n");
return 1;
}
int *values = malloc(count * sizeof *values);
if (values == NULL && count != 0) {
perror("malloc");
return 1;
}
/* use values */
free(values);
values = NULL;Ownership ends with free
Every successful allocation needs one clear owner responsible for free. A leak loses the last pointer without freeing. A dangling pointer still holds an address after free. Double-free and use-after-free are undefined behavior.
realloc may move the block and returns null without freeing the original on failure. Assign the result to a temporary pointer first. Only replace the owner's pointer after success.
int *resized = realloc(values, newCount * sizeof *values);
if (resized == NULL && newCount != 0) {
/* values is still valid */
} else {
values = resized;
}Try it yourself
Explain why values = realloc(values, newSize); can leak memory.
Need a hint?
What happens to the only original pointer when realloc returns null?
Check the worked solution
The assignment overwrites the original pointer with null, losing access to the still-allocated block. Use a temporary pointer.
Quick check
After free(p), which action is valid?
Why this lesson exists
Syllabus mapping
Dynamic memory allocation · Allocating and freeing values and arrays
Maps to course outcomes CO3, CO4, CO5.