Memory leak concepts - Time & Space Complexity
When we talk about memory leaks in C, we want to understand how the program's memory use grows over time.
We ask: Does the program keep using more memory as it runs, and how fast does that happen?
Analyze the time complexity of the following code snippet.
#include <stdlib.h>
void leakMemory(int n) {
for (int i = 0; i < n; i++) {
int *ptr = malloc(sizeof(int));
*ptr = i;
// No free(ptr) here, memory leak occurs
}
}
This code allocates memory inside a loop but never frees it, causing a memory leak.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Memory allocation with
mallocinside a loop. - How many times: The loop runs
ntimes, somallocis calledntimes.
Each loop iteration adds a new memory allocation that is never freed.
| Input Size (n) | Approx. Memory Allocations |
|---|---|
| 10 | 10 allocations leaked |
| 100 | 100 allocations leaked |
| 1000 | 1000 allocations leaked |
Pattern observation: Memory usage grows linearly with n because each iteration leaks one allocation.
Time Complexity: O(n)
This means the number of memory allocations (and leaks) grows directly with the input size.
[X] Wrong: "Calling malloc inside a loop is always safe because the program runs fast enough."
[OK] Correct: Even if the program runs fast, forgetting to free memory causes leaks that build up and can crash the program or slow it down over time.
Understanding how memory leaks grow helps you write better C programs and shows you care about resource management, a key skill in programming.
"What if we added a free(ptr) inside the loop? How would the time complexity and memory usage change?"
Practice
Solution
Step 1: Understand memory allocation
Memory is allocated dynamically using functions like malloc().Step 2: Identify what causes leaks
If allocated memory is not freed using free(), it causes a memory leak.Final Answer:
When allocated memory is not freed after use -> Option AQuick Check:
Memory leak = not freeing allocated memory [OK]
- Confusing memory leak with syntax errors
- Thinking memory leaks happen only on crashes
- Believing memory leaks are about variable count
Solution
Step 1: Recall C memory management functions
C uses malloc() to allocate and free() to release memory.Step 2: Identify correct syntax
free(ptr); is the standard function to free allocated memory.Final Answer:
free(ptr); -> Option AQuick Check:
Use free() to release memory [OK]
- Using delete which is C++ syntax
- Using non-existent functions like release or dispose
- Forgetting to pass the pointer to free()
int *ptr = malloc(sizeof(int));
*ptr = 10;
printf("%d\n", *ptr);
// Missing free(ptr);Solution
Step 1: Analyze memory allocation and assignment
Memory is allocated and 10 is stored at that location.Step 2: Check output and memory freeing
printf prints 10 correctly; missing free() causes leak but no output error.Final Answer:
10 -> Option BQuick Check:
Output prints stored value despite missing free() [OK]
- Assuming missing free causes crash or wrong output
- Confusing memory leak with runtime errors
- Expecting zero or garbage output
char *str = malloc(20); strcpy(str, "Hello World"); // No free(str) called str = malloc(30); strcpy(str, "New String"); free(str);
Solution
Step 1: Trace memory allocations
First malloc(20) is assigned to str, then overwritten by second malloc(30).Step 2: Check freeing of memory
First allocated memory is lost without free, causing memory leak.Final Answer:
Memory leak due to first malloc not freed -> Option DQuick Check:
Overwriting pointer without free causes leak [OK]
- Thinking strcpy causes syntax error
- Assuming double free without repeated free calls
- Believing code is leak-free because free is called once
Solution
Step 1: Understand ownership of allocated memory
The caller owns the memory returned and must free it to avoid leaks.Step 2: Prevent leaks by freeing before reassignment
Calling free() before reassigning pointer prevents losing track of allocated memory.Final Answer:
Always call free() on the returned pointer before reassigning it -> Option CQuick Check:
Free before reuse prevents leaks [OK]
- Assuming function frees memory automatically
- Using global variables without freeing
- Avoiding reuse but causing inefficient memory use
Ready to prove it?
Pass the test and this pattern moves unknown
