malloc, free & Heap Lifetime
The stack is automatic and bounded. The heap is manual and flexible. malloc gives you memory at runtime; free is the promise you make to give it back.
In plain English
malloc borrows a box from the heap, and free returns it. Forget to return it and the pile grows.
Heap allocation with malloc
malloc(size) reserves at least size bytes and returns a pointer to the block, or NULL if allocation fails. The memory is uninitialized. Casting the result of malloc is unnecessary in C. Use sizeof *pointer so the allocation stays correct if the pointed-to type changes. Always check for NULL before using the block.
int *numbers = malloc(10 * sizeof *numbers);
if (numbers == NULL) {
fprintf(stderr, "out of memory\n");
return 1;
}
for (int i = 0; i < 10; i++) {
numbers[i] = i * i;
}free and pointer lifetime
free(pointer) releases the block. Every successful allocation needs a matching free, and you must not use the pointer after freeing it. Set the pointer to NULL after free to reduce dangling-pointer risk. Ownership should be clear: one part of the program is responsible for releasing each allocation.
free(numbers);
numbers = NULL; /* avoid a dangling pointer */Watch it happen
Step through the memory changes one instruction at a time.
step-by-step
Step 1 of 5
Allocate from the heap
malloc(16) returns a heap block. p stores the block address; the bytes are uninitialized.
Key takeaways
- malloc returns uninitialized memory or NULL.
- Use sizeof *pointer to size the allocation.
- free releases a block; do not use the pointer afterward.
- Set pointers to NULL after free.
Common pitfalls
- Forgetting to check malloc for NULL.
- Using memory after free.
- Losing the only pointer to a block and leaking it.
Key focus
- Know the malloc/free lifecycle.
- Expect questions on NULL checks and dangling pointers.
Quick check
1. What does malloc return on failure?
2. What should you do immediately after free(p)?