C in 100 Seconds: malloc and free | Episode 20
Video: C in 100 Seconds: Dynamic Memory — malloc sizeof free | Episode 20 by Taught by Celeste AI - AI Coding Coach
Watch full page →malloc and free — Heap Memory in C
C in 100 Seconds, Episode 20
So far, all our variables have lived on the stack — allocated automatically and freed when the function returns. malloc lets you allocate memory on the heap, where it persists until you explicitly free it.
Allocating Memory
#include <stdlib.h>
int *nums = malloc(5 * sizeof(int));
malloc takes a size in bytes and returns a pointer to the allocated block. 5 * sizeof(int) requests enough space for 5 integers (typically 20 bytes).
Using the Memory
Once allocated, you use it like any array:
for (int i = 0; i < 5; i++) {
nums[i] = (i + 1) * 10;
}
for (int i = 0; i < 5; i++) {
printf("nums[%d] = %d\n", i, nums[i]);
}
Output:
nums[0] = 10
nums[1] = 20
nums[2] = 30
nums[3] = 40
nums[4] = 50
The pointer nums behaves exactly like an array name. Index access works the same way.
Freeing Memory
When you're done, release the memory back to the system:
free(nums);
After free, the pointer is dangling — it still holds the old address, but that memory is no longer yours. Using it after free is undefined behavior.
Why Does This Matter?
Stack memory is fast but limited and automatic. Heap memory is flexible:
- Dynamic sizing — allocate exactly as much as you need at runtime
- Longer lifetime — survives past the function that created it
- Your responsibility — forget to
freeand you leak memory
malloc and free are the core of manual memory management in C. Every data structure that grows at runtime — dynamic arrays, linked lists, hash tables — is built on them.
Full Code
#include <stdio.h>
#include <stdlib.h>
int main() {
int *nums = malloc(5 * sizeof(int));
for (int i = 0; i < 5; i++) {
nums[i] = (i + 1) * 10;
}
for (int i = 0; i < 5; i++) {
printf("nums[%d] = %d\n", i, nums[i]);
}
free(nums);
printf("Memory freed.\n");
return 0;
}
Compile and Run
gcc malloc.c -o malloc
./malloc
Next episode: calloc and realloc — zero-initialized allocation and resizing memory.
Student code: github.com/GoCelesteAI/c-in-100-seconds/episode20