Why dynamic memory is needed in C++ - Performance Analysis
We want to understand why programs sometimes need dynamic memory instead of fixed memory.
How does using dynamic memory affect how long a program takes to run?
Analyze the time complexity of the following code snippet.
#include <iostream>
int main() {
int n;
std::cin >> n;
int* arr = new int[n]; // allocate dynamic array
for (int i = 0; i < n; i++) {
arr[i] = i * 2;
}
delete[] arr;
return 0;
}
This code reads a number n, creates an array of size n in dynamic memory, fills it, then frees it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that fills the array.
- How many times: It runs n times, once for each element.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly with the input size.
Time Complexity: O(n)
This means the time to fill the array grows in a straight line as the array size grows.
[X] Wrong: "Dynamic memory allocation itself takes constant time regardless of size."
[OK] Correct: Allocating large dynamic memory can take longer because the system must find enough space and set it up, so time can grow with size.
Understanding how dynamic memory affects program speed helps you write programs that handle changing data sizes well.
"What if we replaced the for-loop with a recursive function to fill the array? How would the time complexity change?"
Practice
Solution
Step 1: Understand memory allocation timing
Static memory is fixed before running, but dynamic memory is allocated while the program runs.Step 2: Recognize the need for unknown sizes
When the amount of data is not known before running, dynamic memory allows flexible allocation.Final Answer:
To allocate memory during program execution when size is unknown -> Option BQuick Check:
Dynamic memory = flexible size allocation [OK]
- Thinking dynamic memory is for speed only
- Confusing dynamic with static memory
- Believing dynamic memory avoids variables
Solution
Step 1: Recall dynamic allocation syntax
In C++, dynamic memory for an int is allocated using 'new int' and assigned to an int pointer.Step 2: Check pointer declaration
The pointer must be declared as 'int *p' to hold the address of the allocated int.Final Answer:
int *p = new int; -> Option AQuick Check:
Pointer = new type; correct syntax [OK]
- Missing pointer * in declaration
- Wrong order of new and type
- Assigning new int to non-pointer variable
int *arr = new int[3]; arr[0] = 10; arr[1] = 20; arr[2] = 30; std::cout << arr[1] << std::endl; delete[] arr;
Solution
Step 1: Understand array allocation and assignment
Dynamic array of size 3 is created, and values 10, 20, 30 are assigned to indices 0, 1, 2 respectively.Step 2: Identify output statement
The code prints arr[1], which holds the value 20.Final Answer:
20 -> Option DQuick Check:
arr[1] = 20 printed [OK]
- Confusing index positions
- Forgetting to use delete[] for arrays
- Assuming compilation error due to dynamic array
int *p; p = new int(5); std::cout << *p << std::endl; // missing delete statement
Solution
Step 1: Check dynamic allocation correctness
Pointer p is declared and assigned new int(5), which is correct syntax.Step 2: Identify missing memory management
Allocated memory is not freed with delete, causing a memory leak.Final Answer:
Missing delete to free allocated memory -> Option AQuick Check:
Always delete after new to avoid leaks [OK]
- Ignoring memory leaks
- Thinking new int(5) is wrong syntax
- Assuming pointer must be initialized differently
Solution
Step 1: Understand the problem of unknown input size
Since the number of inputs is unknown, fixed-size arrays may waste memory or be too small.Step 2: Choose flexible memory allocation
Dynamically allocated arrays can be resized (e.g., by allocating new larger arrays and copying data) to fit input size.Final Answer:
Use a dynamically allocated array and resize it as needed -> Option CQuick Check:
Dynamic resizing fits unknown input sizes [OK]
- Using fixed arrays that may overflow
- Not allocating memory before use
- Ignoring memory management when resizing
Ready to prove it?
Pass the test and this pattern moves unknown
