Why we call memory created using "new" keyword "dynamic memory" since it is also a fixed memory

Viewed 105

Array created this way int a[5] contains 5 integer memory blocks and memory can't be changed at runtime. Array created this way int *ptr=new int[5] also contains 5 integer blocks and in this case too memory cant be increased and decreased at runtime, so, from which perspective it is called dynamic memory.

2 Answers

The colloquial term "dynamic memory" comes from the language defined term "dynamic storage duration". See Storage duration :

dynamic storage duration. The storage for the object is allocated and deallocated per request by using dynamic memory allocation functions. See new-expression for details on initialization of objects with this storage duration.

Objects created with new or new[] and destroyed with delete or delete[] have dynamic storage duration.

It is dynamic because the lifetime starts and ends whenever the developper wants it to. Every other storage durations have strict rules about when life time starts and when it ends. It has nothing to do sizes of arrays or resizing arrays. Non-array objects can have dynamic storage duration too.

Consider the following case

#include <iostream>

int main()
{
    int size;
    std::cin>>size;
    int array1[size]; //compile error, the size of static array must be known at compile time
    int* parr=new int[size]; //ok, size of an dynamic array can be unveiled on runtime.
    ....
    ....
}

So the dynamic term refers to the fact that user can decide the size of the array whenever he/she wants to.

Related