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);