Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory allocation in C++?

Why does this work?

    #include <iostream>    

    int main()
    {
        std::cout << "Enter a number: ";
        int arraySize;
        std::cin >> arraySize;

        int array[arraySize];

        for(int element : array)
        {
            element = 42;
            std::cout << element << "\n";
        }

        std::cout << "Array size: " << sizeof(array) << "\n";
        std::cout << "Element count: " << sizeof(array)/sizeof(int);

        return 0;
    }

My understanding of dynamic memory allocation in C++ tells me that one case where it is needed is when you do NOT know the amount of memory you need to allocate at compile-time. In this program, clearly the array size is not known when the program is compiled, but is dynamic, as it can change with the value the user enters.

Here is a program run after it is successfully compiled(warning and error free) with:
g++ program.cpp -std=c++11 -o program.exe

Enter a number: 12
42
42
42
42
42
42
42
42
42
42
42
42
Array size: 48
Element count: 12

As you can see, an array was created with a user-defined amount of elements, each was successfully assigned to 42, and proven to exist with the sizeof() operator.

Why does this not count as dynamic memory allocation and compile?

like image 448
Alex Avatar asked Mar 08 '23 09:03

Alex


1 Answers

This declaration of variable-length array (VLA) is not standard:

int array[arraySize];

The reason this line compiles with g++ is that the compiler has provided this functionality as an extension:

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

like image 189
Sergey Kalinichenko Avatar answered Mar 19 '23 05:03

Sergey Kalinichenko