0

Which is more memory efficient and why between declaring the size of an array at run time using the 'new' keyword for dynamic memory allocation and using the method below:

#include <iostream>

using namespace std;

int main ()
{
    int size;

    cin >> size;

    int a[size];
}

Dynamic Memory allocation using 'new' key word

#include <iostream>

using namespace std;

int main ()
{
    int *array {nullptr};
    
    int size;

    cin >> size;

    array = new int[size];
     
    delete [] array;
}

2 Answers2

1

Allocating memory on the stack is much faster (essentially by changing the stack pointer). And you don't have to worry about managing it, it is freed when the function exits. But the stack size is usually much smaller than the heap size. For small local objects, use the stack, for large ones and those whose lifetime is outside the scope of the function - heap.

alex_noname
  • 26,459
  • 5
  • 69
  • 86
  • 1
    In the context of the OP's code snippet, using a VLA extension is both nonportable and also dangerous, since the size is influenced by user input (easy way to generate stack overflows and introduce vulnerabilities). May be worth mentioning – Human-Compiler Dec 22 '20 at 18:02
0

both have pros and cons depends on what you want to achieve. memory allocation and deallocation are automatically done by the compiler when allocated on the stack while on the heap you have to allocate and dedicate the memory also on the heap you can relocate and resize memory required as per your requirement which is not possible on stack.