Open In App

Introduction to Stack memory

The stack is a segment of memory that stores temporary variables created by a function. In stack, variables are declared, stored and initialized during runtime.

When we compile a program, the compiler enters through the main function and a stack frame is created on the stack. A structure, also known as an activation record, is the collection of all data on the stack associated with one subprogram call. The main function and all the local variables are stored in an initial frame.

It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased. The stack section mostly contains methods, local variables, and reference variables.

Advantages of Stack Memory:

Disadvantages of Stack Memory:

Example of creating memory in Stack:




int Geeks()
{
    // Nothing allocated yet excluding the
    // pointer itself, which is allocated
    // here on the stack.
    char* p;
 
    // Memory allocated on the stack.
    bool flag = true;
 
    if (flag) {
 
        // Create 1000 bytes on the stack
        char buffer[1000];
 
        // Create 1000 bytes on the heap
        p = new char[1000];
    }
 
    // Buffer is deallocated here but pointer
    // p is not Here occurs a memory leak,
    // We have to call delete[] p;
}




public static int geeks() {
    // Nothing allocated yet excluding the
    // pointer itself, which is allocated
    // here on the stack.
    char[] p;
 
    // Memory allocated on the stack.
    boolean flag = true;
 
    if (flag) {
        // Create 1000 bytes on the stack
        char[] buffer = new char[1000];
 
        // Create 1000 bytes on the heap
        p = new char[1000];
    }
 
    // Buffer is deallocated here but pointer
    // p is not Here occurs a memory leak,
    // We have to call delete[] p;
    return 0;
}
 
// This code is contributed by Utkarsh.

Points to Remember:

It is stored in computer RAM just like the heap.
It is implemented with the stack data structure.
Stack memory will never become fragmented
It stores local variables and returns addresses, used for parameter passing.
Variables created on the stack will go out of scope and are automatically deallocated.
Variables created on the stack can be used without pointers.
We can use stack memory to store the data if we know exactly how much data you need to allocate before compile time and if it is not too big.
It usually allocates maximum sizes which are determined during the execution of the program.
Some issue like Stack overflow arises when too much of the stack memory is used (mostly from infinite or too deep recursion, substantial allocations).

Article Tags :