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.

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.

raja
Published on 18-Jun-2019 12:35:06
Advertisements