Memory leak concept in C++ - Time & Space Complexity
When we talk about memory leaks, we want to understand how the program's use of memory grows over time.
We ask: Does the program keep using more memory as it runs, even when it shouldn't?
Analyze the memory usage of the following code snippet.
void createArray(int n) {
int* arr = new int[n];
// Use the array for some work
// Missing delete[] arr; causes memory leak
}
This code creates an array of size n but never frees the memory, causing a memory leak.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Allocating memory for an array of size n.
- How many times: Once per function call, but memory is never freed.
As n grows, the amount of memory allocated grows linearly, but since it is never freed, total memory use keeps increasing.
| Input Size (n) | Approx. Memory Allocated |
|---|---|
| 10 | Memory for 10 integers |
| 100 | Memory for 100 integers |
| 1000 | Memory for 1000 integers |
Pattern observation: Memory use grows directly with n and never decreases because memory is not released.
Memory Usage Complexity: O(n)
This means the memory allocated grows in direct proportion to the input size n, and without freeing, memory use keeps increasing.
[X] Wrong: "If I allocate memory once, it won't affect the program's memory over time."
[OK] Correct: Even one allocation that is never freed adds up if the function runs multiple times, causing memory to grow and possibly crash the program.
Understanding how memory grows and leaks helps you write safer programs and shows you care about resource management, a key skill in programming.
"What if we added a delete[] statement to free the memory? How would the memory usage change?"