Stack vs Heap

In C and C++, the memory assigned to a program in typical architecture is divided into four parts:

  1. Code(Text): set of program instructions.
  2. Global/Static: For global variables and static variables.
  3. Stack: Information of function calls and local variables are stored in this part. Memory assigned to the stack depends on the compiler design.Example with code
    #include <iostream>
    using namespace std;
    
    int sum(int a,int b){
    return a+b;
    };
    
    int main()
    {
    int x = 5, y = 6;
    cout << "Sum of two numbers: " << sum(x,y) << endl;
    return 0;
    }
    

    In the above example, a stack is empty before the execution of program but when program starts executing and now the top of a stack is local variables (i.e. x and y) and after that top of the stack is cout instruction which calling to the sum function and now the top of the stack is sum function. The computer only executes the top of the stack instruction and when a top of the stack instruction is finished then the control of execution of the program is transfer to the below instruction (which is now the top of the stack because instruction on the top of this instruction is finished). When the stack is empty it means a program is executed.

    Note: If our stack is going beyond the reserved memory of the stack and our program exhausted all the memory of the stack called stack overflow and in this case, our program is crashed. For eg. bad recursion and our programs goes infinite loop.

  4. Heap (free store of memory): Allocating large amount of memory then we have a heap or giving the memory of the array at run-time. The programmer can totally control to how much memory can use from the heap and the size of the heap varying according to system time.
    To use dynamic memory of heap in C++ we use new and delete operators.Code:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int *p;
        // Allocating memory of size int in heap using new operator
        p = new int;
        *p = 10;
        cout << "Value of p: " << *p << endl;
        delete p;
        return 0;
    }