Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are C-style arrays with the run-time length allocated on the heap? [C++]

I know fixed-size arrays in C++ are allocated on the stack, and I know that a dynamic-sized array created using new[] keyword will be allocated on the heap.

But consider this snippet of code:

std::cout << "Enter a length of the array: "
int length{};
std::cin >> length;

int arr[length]{};

for (int i{ 0 }; i < length; ++i)
{
    arr[i] = i;
    std::cout << arr[i] << ' ';
}
std::cout << '\n'

It compiles without a problem. So am I right in assuming that such arrays are implicitly placed on the heap? And if so, how does it works, is the memory used by this array freed after implicitly too?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is not standard C++.

The compiler you are using supports a mixture of C and C++ features in the same file. The support for variable-length arrays is a C feature.

Variable-length arrays are stored on the stack, typically. This is more or less equivalent to allocating the array with alloca().

(I recommend avoiding variable-length arrays. Since they are not part of C++, they may interact poorly with some C++ features, and most C++ compilers will not support them at all. You probably want to use std::vector instead.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading