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;
}
8
  • 7
    int a[size]; is not valid C++ (use VLA extension). Commented Dec 22, 2020 at 11:36
  • why is ```int a[size]`` invalid and it compiles without errors? Commented Dec 22, 2020 at 11:43
  • 1
    int a[size]; does not compile on MSVC: godbolt.org/z/xo13cW - as mentioned before, it is not standard C++, it uses an extension that some compilers support Commented Dec 22, 2020 at 11:45
  • Does this answer your question? c++ dynamic memory allocation using "new" Commented Dec 22, 2020 at 11:46
  • 3
    second snippet has memory leak. prefer std::vector over raw owning pointer. Commented Dec 22, 2020 at 12:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.