Which of the following best explains why dynamic memory is needed in C++?
Think about when you don't know how much memory you need before the program runs.
Dynamic memory allows programs to request memory while running, which is useful when the amount of data is not fixed or known in advance.
What is the output of this C++ code?
#include <iostream> int main() { int n = 3; int* arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = i * 2; } std::cout << arr[2] << std::endl; delete[] arr; return 0; }
Look at the loop and what values are assigned to each element.
The loop assigns arr[i] = i * 2. For i=2, arr[2] = 2 * 2 = 4.
What will happen if you run this C++ code repeatedly without freeing the allocated memory?
#include <iostream> int main() { while(true) { int* ptr = new int[1000]; // no delete[] ptr; } return 0; }
Think about what happens when memory is allocated but never released.
Not freeing dynamic memory causes a memory leak, which can slow down or crash the program as memory runs out.
Why are static arrays not always enough, making dynamic memory necessary?
Think about when you need to decide the size of an array while the program runs.
Static arrays require size known before running the program. Dynamic memory allows allocating memory based on runtime needs.
In which scenario is dynamic memory allocation most beneficial?
Think about programs that grow or shrink data while running.
Dynamic memory is useful when data size is not fixed and can change during program execution.