C Memory Management
C memory management means requesting memory while the program runs and giving it back when you are done. Local variables live on the stack and disappear automatically, but memory from malloc lives on the heap until you call free.
Allocating Memory with malloc
malloc takes a number of bytes and returns a pointer, or NULL if it fails. Always check for NULL and always free what you allocate.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *arr = malloc(n * sizeof *arr);
if (arr == NULL) {
printf("Out of memory\n");
return 1;
}
for (int i = 0; i < n; i++) arr[i] = i * i;
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}0 1 4 9 16
calloc and realloc
calloc allocates and sets every byte to zero. realloc resizes an existing block, possibly moving it, so assign the result to a temporary pointer first.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *data = calloc(3, sizeof *data); // {0, 0, 0}
if (!data) return 1;
int *bigger = realloc(data, 5 * sizeof *data);
if (!bigger) { free(data); return 1; }
data = bigger;
data[3] = 7;
data[4] = 9;
for (int i = 0; i < 5; i++) printf("%d ", data[i]);
printf("\n");
free(data);
return 0;
}0 0 0 7 9
Common Memory Bugs
- Memory leak: forgetting to call free, so memory is never returned.
- Dangling pointer: using a pointer after its memory was freed. Set it to NULL after free.
- Double free: calling free twice on the same pointer.
- Buffer overflow: writing past the end of an allocated block.
- Tools like Valgrind and the -fsanitize=address compiler flag find these bugs for you.
Stack vs Heap in C
The stack is fast and automatic but small and limited to the lifetime of a function call. The heap is large and flexible, and data there survives until you free it, which is why functions that build lists or load files usually allocate on the heap and return a pointer.
Frequently asked questions
What is the difference between malloc and calloc?
malloc allocates memory without initializing it, so it contains garbage. calloc takes a count and an element size and sets all bytes to zero.
Do I need to cast the result of malloc in C?
No. In C, void * converts automatically to any object pointer type, so a cast is unnecessary. C++ does require the cast.
What happens if I do not free memory in C?
The memory stays reserved until the program exits, which is a memory leak. In long-running programs, leaks slowly consume all available memory.