Memory allocation and deallocation in C++ - Time & Space Complexity
When we allocate or free memory in a program, it takes some time. Understanding how this time grows helps us write faster programs.
We want to know how the cost of memory allocation and deallocation changes as the program runs more or uses more memory.
Analyze the time complexity of the following code snippet.
int* allocateArray(int n) {
int* arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = 0;
}
return arr;
}
void freeArray(int* arr) {
delete[] arr;
}
This code allocates an array of size n, initializes it, and then frees the memory.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sets each element to zero.
- How many times: It runs exactly n times, once for each element.
As n grows, the number of times we set elements grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to allocate and initialize memory grows in a straight line with the size of the array.
[X] Wrong: "Memory allocation is always a constant time operation, no matter the size."
[OK] Correct: Allocating memory often involves setting up space and initializing it, which takes time proportional to the size requested.
Understanding how memory operations scale helps you write efficient code and explain your choices clearly in interviews.
"What if we removed the loop that initializes the array? How would the time complexity change?"
Practice
new operator do in C++?Solution
Step 1: Understand the role of
Thenewnewoperator allocates memory dynamically on the heap during program execution.Step 2: Differentiate from other memory actions
It does not delete memory or allocate on the stack; it only reserves space on the heap.Final Answer:
Allocates memory on the heap for a variable or object -> Option AQuick Check:
new= allocate heap memory [OK]
- Confusing new with delete
- Thinking new allocates on stack
- Assuming new copies data
new for a single integer variable?Solution
Step 1: Identify correct deallocation for single object
Memory allocated withnewfor a single variable must be freed withdelete, notdelete[].Step 2: Exclude incorrect options
free()is for C-style malloc, and setting pointer to nullptr does not free memory.Final Answer:
delete ptr; -> Option CQuick Check:
Single object deallocation = delete [OK]
- Using delete[] for single variable
- Using free() instead of delete
- Only setting pointer to nullptr without delete
int* ptr = new int(10);
std::cout << *ptr << std::endl;
delete ptr;
Solution
Step 1: Analyze memory allocation and initialization
The pointerptrpoints to a new integer initialized with 10.Step 2: Understand output before deletion
Dereferencing*ptrprints 10 before memory is deleted.Final Answer:
10 -> Option BQuick Check:
Dereference new int(10) = 10 [OK]
- Assuming output is 0 or garbage
- Thinking delete affects output before cout
- Confusing syntax causing compile error
int* arr = new int[5];
delete arr;
Solution
Step 1: Check allocation type
Memory allocated withnew[]must be deallocated withdelete[].Step 2: Identify mismatch in deallocation
Usingdeleteinstead ofdelete[]causes undefined behavior.Final Answer:
Should use delete[] instead of delete -> Option DQuick Check:
Array deallocation = delete[] [OK]
- Using delete for arrays
- Ignoring pointer initialization
- Assuming no error in mismatched delete
Solution
Step 1: Allocate and initialize array to zero
Usingnew int[10]()allocates an array of 10 integers and initializes all to zero.Step 2: Properly deallocate array memory
Memory allocated withnew[]must be freed withdelete[]to avoid leaks or undefined behavior.Final Answer:
int* arr = new int[10](); delete[] arr; -> Option AQuick Check:
new[] with () + delete[] = safe zero-init array [OK]
- Using delete instead of delete[] for arrays
- Mixing malloc/free with new/delete
- Allocating single int instead of array
Ready to prove it?
Pass the test and this pattern moves unknown
