Stack and heap addresses

In this simple line of code, my understanding is that the "new" below simply initializes the data structure, and returns a pointer to the start of that data structure.

However the subtlety here is that this code allocates memory to store the pointer A on the stack, and memory to store the structure itself on the heap!

What's the reason for why the memories are allocated separately on the stack and on the heap this way?

 
St *A = new St[5];
Last edited on
Non-static local variables are stored on the stack so that they are automatically cleaned up when the function returns.
Presumably your pointer is a non-static local variable, so its value is on the stack.
The heap values can last after the function returns (in which case you should return the pointer value so that you don't lose its address, leaking memory).
Awesome! Thanks dutch.
Topic archived. No new replies allowed.