If I declare an array inside a function, is the memory deallocated upon leaving the function?
I wouldn’t have thought so, however, when I declare an array inside a function, write the pointer to the array to a global variable and then attempt (outside the function) to dereference the pointer to an element in the array, I get a memory access violation. I don’t get a memory access violation if I use the same code inside the function.
Clarification would be much appreciated.
Thanks in advance.
An array declared in a function is allocated on the program stack. When your program exits the function, the local variables on the stack are popped and the memory containing the array is no longer accessible. The alternative is to new an array pointer which is allocated on the program heap, will survive the function exit and must subsequently be delete‘d or a memory leak will occur.
A fairly general explanation of the program stack is a block of memory set aside to hold the local variables for your functions. When a function is called, the amount of memory required to hold the local variables for the function is pushed on the top of the stack, i.e the stack pointer is moved up by that amount. When the function exits, that exact amount of memory is popped off the top of the stack and the stack pointer moves back down to its previous location prior to the function call. The program heap on the other hand is memory that doesn’t have stack semantics and is used when a function requests a new block of memory. The program is then responsible for managing the deallocation of that memory.
Smart pointers are often used in C++ to automatically handle the allocation and deallocation of memory to avoid bugs/memory leaks associated with memory management.
A quick google threw up this explanation of stack versus heap in C++.