Proper stack and heap usage in C++?

C++Server Side ProgrammingProgramming

The stack − All variables declared inside the function will take up memory from the stack. So, any local variable inside a function lives on the stack.

The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs. So If we want something to live longer than the function that declared it, we must allocate it on the heap.


int main() {
   int a; //get memory allocated on stack.
   int *ptr=new int[7]; //memory for 7 integers allocated on heap.

The main issue in heap memory is fragmentation whereas memory shortage problem is seen more likely in stack. Memory size can be changed in heap which can’t be changed in stack.

Updated on 30-Jul-2019 22:30:26