Search code examples
c++arraysruntimedynamic-memory-allocationstatic-memory-allocation

What kind of memory allocation (dynamic or static )does the following code do?


    #include <iostream>
using namespace std;

int main() {
    int n;
    cin>>n;
    int arr[n];
    return 0;
}

The size of the array is entered by the user at the run time, but the memory is allocated on the stack. What kind of memory allocation is this? Static or Dynamic ?


Solution

  • with all the reserve associated to the variable length array in C++, this is a it is a dynamic allocation in the stack

    • dynamic because the size if unknown at compile time
    • and in the stack rather than in the heap because not like int * arr = new arr[n]; even this is dependent on the compiler. The associated problem is because the size is unknown at compile time the offset in the stack of some other local variables cannot be known statically too

    For instance using g++ :

    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        cin>>n;
        int arr[n];
        int other;
        
        cout << &n << ' ' << arr << ' ' << &other << ' ' << new int[n] << endl;
        return 0;
    }
    

    Compilation and execution :

    pi@raspberrypi:/tmp $ g++ -Wall c.cc
    pi@raspberrypi:/tmp $ ./a.out
    10
    0xbe9d825c 0xbe9d8230 0xbe9d8258 0xd84868
    pi@raspberrypi:/tmp $ 
    

    Visibly arr is placed in the stack between n and other, the heap being elsewhere in memory


    Even if your compiler like g++ allows variable length array it is not recommended to use them because :

    • the size of the stack is always much less than the size of the heap
    • that makes the access to some other local variables more expensive because their offset/address in the stack need to be computed rather than to be statically known