Think of malloc (borrow) and free (return) as a pair that must always match
Start with small sizes β around 10 elements β to build up your intuition
Build the habit of setting p = NULL; right after calling free
A memory leak won't crash your program instantly, so don't let it block your progress
π‘ Tip: pair every malloc with a free, and always null-check the return value. That's enough to get you started.
Why do we need dynamic memory?
Up to this point, arrays have had their size fixed at compile time, as in int a[5];. But in real-world programs, you often don't know the element count until runtime.
The fixed-array limitation
int a[100];
Can't hold more than 100 items, and if you have fewer, the remaining memory is wasted.
With dynamic allocation
int *a = malloc(n * sizeof(int));
Allocate exactly n items; use realloc if you need to resize later.
malloc and free
malloc allocates the number of bytes you ask for and returns a pointer to the start of that block. When you're done with it, release it with free.
#include<stdlib.h> // needed for malloc, free
int *p = (int *)malloc(sizeof(int) * 5); // allocate space for 5 ints (= 20 bytes)
for(int i = 0; i < n; i++){
printf("Item %d: ", i+1);
scanf("%d", &data[i]);
}
// compute the sum
int sum = 0;
for(int i = 0; i < n; i++) sum += data[i];
printf("Sum: %d\n", sum);
free(data); // do not forget to free
p[i] and *(p + i) mean the same thing β a pointer from malloc can be indexed with [] just like an array.
Memory leaks β what happens when you forget to free
If you forget to free memory you got from malloc, that memory stays reserved until the program ends. This is called a memory leak.
Memory leak simulation
Click the buttons to watch the memory change.
In long-running programs (servers, embedded systems, and so on), memory leaks are fatal. Even small leaks accumulate over time and eventually exhaust memory, crashing the program. Make it a habit: if you malloc, you free.
π₯ Heap timeline — visualize the malloc/free flow
Watch how the heap changes as you call malloc and free. Step through five scenarios to see the classic bugs: double-free, use-after-free, memory leaks, and fragmentation.
π§ͺ Pick a scenario
Pick a scenario to start.
// No scenario selected
Heap state
In use: 0 BPeak: 0 Bmalloc: 0free: 0
Operation log
(Pick a scenario and press βΆ)
π‘ How to read it: each block shows its ID, address, size, and state (π’ in-use or π΄ freed). Illegal operations like double-free or use-after-free are flagged in red.
Try it yourself β dynamic memory
Allocate a dynamic array, fill it with values, and compute their sum.
dynamic.c
Output
Click Run...
π‘ Try these ideas too
Let the user choose the array size with scanf
Allocate with calloc for zero-initialized memory
Grow the array with realloc
Think about what happens if you forget free β the dreaded memory leak
A. Use a plain array when the size is known at compile time, and malloc when the size is only known at runtime. If you know the maximum is 100, use an array; if the user enters the count, use malloc. Arrays are generally faster and safer, so prefer them when you can.
Q. What happens if I forget to call free?
A. You get a memory leak. The allocated memory becomes unreachable, and in long-running programs the available memory gradually dwindles until the process runs out of memory and crashes. The rule is simple: if you malloc, you must free. Allocation and release always need to be paired.
Q. What is the difference between malloc and calloc?
A. malloc allocates the requested size but leaves the memory uninitialized. calloc zeros the memory for you. Its signature is calloc(count, size) β for example, calloc(10, sizeof(int)) allocates 10 ints, all initialized to zero.
Q. What exactly is a memory leak?
A. A memory leak is memory that was allocated but never freed β it stays wasted until the program exits. A single leak rarely matters, but leaks inside a loop pile up and eventually exhaust memory. Tools like valgrind --leak-check=full are commonly used to detect them.
Review Quiz
Check your understanding of this lesson.
Q1. What happens if you never free memory obtained from malloc?
It's automatically freed
A memory leak occurs
Compile error
Memory from malloc must be freed explicitly. If you forget, it leaks.
Q2. What does malloc(sizeof(int) * 10) do?
Allocates enough space for 10 ints
Allocates enough space for 1 int
Allocates exactly 10 bytes
sizeof(int) * 10 computes the byte size for 10 ints, and malloc allocates that many bytes on the heap.
Q3. What should you do with a pointer right after calling free?
Keep using it
Assign NULL to it
Nothing more is needed
After free, the pointer becomes a "dangling pointer." Setting it to NULL makes any accidental reuse easy to detect.