1

I'm a little confused about dynamic memory allocation and I was hoping someone could help clear it up for me.

So say we have a program:

int length = 0;

cout << "Enter the size of the array" << endl;
cin >> length;
cin.ignore();

int numbers[length];

Wouldn't this still be dynamic memory allocation since the array size is being defined at runtime after the user enters in the specified length?

vs using:

int numQuestions = 0;

cout << "How many questions would you like to add?" << endl;
cin >> numQuestions;
cin.ignore();

Question *newQuestions = new Question[numQuestions];

ndubs18
  • 11
  • 2
  • 1
    The first example is not standard C++, which does not have variable-length arrays, as such your question is moot. You're using a compiler extension. – Sam Varshavchik Nov 25 '19 at 00:39
  • Arrays with Runtime Bound were proposed into C++14 in n3639 but voted out so it will probably take some time until someone resurrects that proposal. – Öö Tiib Nov 25 '19 at 01:10
  • @ÖöTiib - I doubt it will be resurrected. VLAs were optional in C99 and formally removed from the C standard in 2011 - and the reasons were based on assessed disadvantages in C. That weakened any justification based on C compatibility. Furthermore, most of the down-sides of VLAs for C are also applicable to C++. The feature also doesn't play too well with the C++ object model (constructors, destructors, etc) and C++ also provides alternatives (like standard containers) that are considered preferable to using any raw array construct in C++. – Peter Nov 25 '19 at 01:36

1 Answers1

1

What's the difference? Dynamic memory is allocated on the heap, but arrays are allocated on the stack. Because the memory for int numbers[length] is allocated on the stack, it's not considered dynamic memory allocation. More importantly, you can't return a pointer to an array allocated this way, because that array is a local variable that gets destroyed when the function exits.

That's the purpose of dynamic allocation - dynamic allocation allows memory to stick around for as long as you need it, and it won't go away until delete is called on the pointer to the memory.

Also, it should be noted that declaring an array with a size determined at run-time is non-standard C++ that's supported by some compilers as an extension.

So what's best practice? Using raw pointers is the old way of doing stuff. It's error-prone because you might forget to delete the memory, or if there's an exception, the code to delete the memory might get bypassed. This causes a memory leak.

If you use std::vector instead, you get the following benefits:

  • You can determine the size at run-time,
  • You can return a vector from a function,
  • The memory allocated by the vector automatically gets deleted, so there won't be a memory leak.

How do I use std::vector?

It's pretty simple! Just replace

int numbers[length];

with

std::vector<int> numbers(length);
Alecto Irene Perez
  • 10,321
  • 23
  • 46