1
    #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 ?

  • 7
    It's not valid c++. That's what. – Captain Giraffe Jul 05 '20 at 12:50
  • 1
    I think Variable Length Arrays are another category altogether (note that C++ doesn't allow them, but some compilers allow them as an extension). – Yksisarvinen Jul 05 '20 at 12:52
  • You would need to read your compiler manual to find out how this extension (variable length arrays) was implemented. Or you could try inspected the generated code. – Richard Critten Jul 05 '20 at 12:54
  • You also probably want to ask if it its a stack frame allocation or a free memory allocation. Regardless you want to check out the g++ extension on variable length arrays. https://stackoverflow.com/questions/39334435/variable-length-array-vla-in-c-compilers – Captain Giraffe Jul 05 '20 at 12:55

2 Answers2

2

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
bruno
  • 32,421
  • 7
  • 25
  • 37
  • https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html supports this. – Captain Giraffe Jul 05 '20 at 13:00
  • @CaptainGiraffe yes I know g++ supports them, but thank you for the link – bruno Jul 05 '20 at 13:01
  • Thank you for this. Keeping this in mind, I now also wanted to know the difference between dynamic memory allocation on the stack and dynamic allocation on the heap? –  Jul 05 '20 at 13:15
-1

This is static memory allocation but in static memory allocation you can't take size from user. In order to take size from user you must do dynamic memory allocation.