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 if You Forget free
If you forget to free the memory you got from malloc, it stays reserved until the program ends. That's called a memory leak.
Memory leak simulation
Press the buttons to watch the memory change.
In long-running programs (servers, embedded systems), memory leaks are fatal. Even small leaks accumulate and eventually cause the program to run out of memory and crash. Make it a habit: if you malloc, you free.
Try It Yourself β Dynamic Memory
Allocate a dynamic array, fill it with values, and compute the sum.
dynamic.c
Output
Click Run...
π‘ Try these ideas too
Size the array by user input via scanf
Allocate with calloc (zero-initialized)
Grow the array with realloc
Think about what happens if you forget free (memory leak)
A. Use an array when the size is known at compile time, and malloc when it is determined 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 possible.
Q. What happens if I forget to call free?
A. You get a memory leak. The allocated memory remains unusable, and in long-running programs memory gradually dwindles until the program runs out of memory and crashes. The rule is: if you malloc, you must free. Allocation and release must 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), e.g. calloc(10, sizeof(int)) allocates 10 ints initialized to zero.
Q. What exactly is a memory leak?
A. A memory leak is memory that was allocated but never freed, so it is wasted until the program exits. A single leak rarely matters, but leaks inside a loop accumulate and eventually exhaust memory. Tools like valgrind --leak-check=full are used to detect them.
Quick Quiz
Check your understanding of this lesson.
Q1. What happens if you do not free memory obtained from malloc?
It is automatically freed
A memory leak occurs
Compile error
Memory from malloc must be freed explicitly; otherwise it leaks.
Q2. What does malloc(sizeof(int) * 10) do?
Allocates space for 10 ints
Allocates space for 1 int
Allocates exactly 10 bytes
sizeof(int) * 10 computes the byte size for 10 ints; 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 needs to be done
A pointer after free is a "dangling pointer." Setting it to NULL makes accidental reuse easy to detect.