I want to know where is my array stored if it has variable size such as in the code below this is because in my textbook it says that during runtime memory is allocated to the heap to my understanding, but it seems that it actually allocated to the stack can someone clarify how stack and heap memory allocation actually works.
#include<iostream>
using namespace std;
int main(){
int Array_size;
cin >> Array_size;
int array[Array_size];
return 0;
}
Your book is wrong, or you are misreading it.
A Variable-Length Array (a non-standard extension implemented by few C++ compilers) is always allocated in automatic memory (ie, on the stack), never in dynamic memory (ie, on the heap). The array's memory is reclaimed by the compiler when the array goes out of scope, just like any other local variable.
Dynamic memory is allocated only by the new
operator, or by the [std::](m|c)alloc()
functions.