Proper stack and heap usage in C++?


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.

Example

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

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements