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?"
Practice
What is a memory leak in C++?
Solution
Step 1: Understand memory allocation
Memory allocated withnewmust be freed withdelete.Step 2: Define memory leak
If memory is allocated but not freed, it stays reserved and causes a leak.Final Answer:
When allocated memory is not released back to the system -> Option CQuick Check:
Memory leak = not freeing allocated memory [OK]
- Confusing memory leak with slow program
- Thinking unused variables cause leaks
- Mixing memory leak with logical errors
Which of the following C++ code snippets correctly frees allocated memory?
int* ptr = new int(5); // What should be done next?
Solution
Step 1: Identify allocation method
Memory is allocated withnew, so it must be freed withdelete.Step 2: Match correct freeing syntax
free()is formalloc(), notnew. Setting pointer to nullptr does not free memory.Final Answer:
delete ptr; -> Option BQuick Check:
Use delete for new, free for malloc [OK]
- Using free() with new
- Just setting pointer to nullptr without delete
- Allocating new memory without deleting old
What is the output of this C++ code?
int* ptr = new int(10); ptr = new int(20); std::cout << *ptr << std::endl;
Solution
Step 1: Analyze pointer reassignment
First, ptr points to 10. Then ptr is reassigned to new int(20) without deleting old memory.Step 2: Determine output
Pointer now points to 20, so output is 20. The old memory is leaked but does not affect output.Final Answer:
20 -> Option DQuick Check:
Pointer points to last new value = 20 [OK]
- Expecting output 10 after reassignment
- Thinking code causes compile error
- Confusing memory leak with runtime error
Find the memory leak in this code and fix it:
void func() {
int* arr = new int[5];
arr = new int[10];
delete[] arr;
}Solution
Step 1: Identify memory allocations
First, arr points to array of 5 ints, then reassigned to array of 10 ints without deleting first.Step 2: Fix memory leak
Delete the first array before reassigning arr to avoid leak. Usedelete[]for arrays.Final Answer:
Delete first array before reassigning arr -> Option AQuick Check:
Delete old array before new assignment [OK]
- Not deleting first allocated array
- Using delete instead of delete[] for arrays
- Ignoring memory leak warnings
You have a class that allocates memory in its constructor using new. Which approach best prevents memory leaks?
Solution
Step 1: Understand manual memory management risks
Manually calling delete and following Rule of Three is error-prone and can cause leaks if forgotten.Step 2: Use smart pointers for safety
Smart pointers automatically free memory when no longer used, preventing leaks safely and easily.Final Answer:
Use smart pointers like std::unique_ptr to manage memory automatically -> Option AQuick Check:
Smart pointers prevent leaks automatically [OK]
- Relying only on manual delete
- Avoiding new but not managing memory
- Mixing malloc/free with new/delete
Ready to prove it?
Pass the test and this pattern moves unknown
