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

    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 :