March 29, 2023

New and Delete Operators

Posted on March 29, 2023  •  2 minutes  • 338 words

C++ allows us to create variables at runtime. The variable can be created in Stack memory or Heap memory.

Memory Layout in C++

output

Stack Memory

Functions are allocated stack memory every time they are called by the machine. Whenever a new local variable is declared, more stack memory is allocated to store the variable in that function.

Stacks grow downward when such allocations are made. All local variables of this function become invalid after the function returns, since the stack memory of this function is deallocated.

Allocation and deallocation of stack memory are automatically handled.

Heap Memory

A variable or array can be created during program execution, which is known as dynamic memory allocation. Dynamically created variables or arrays are stored in heap memory.

Note

We must deallocate the dynamically allocated memory after the use of varibale. Other wise it may cause the memory leak.

Memory Management

1. Allocation of memory in Heap (new operator)

To allocate a memory in heap we need to use a special keyword or operator known as new.

new opeartor returns a memory address after allocating a desired memory in heap. So we need to use pointer to store the memory address.

Syntax :

data_type *ptr_variable;
ptr_variable = new data_type(arguments);

Example

int *ptr;
ptr = new int(10);

2. Deallocation of memory in Heap (delete operator)

we can use delete operator/keyword to deallocate the dynamically allocated memory.

Syntax :

delete ptr_variable;

Example :

int *ptr;
ptr = new int(10);

delete ptr;

Example code for Stack and Heap allocation

#include<iostream>

//Stack allocation
void stackAllocation()
{
    int x = 100;
    int *ptr;
    ptr = &x;
    std::cout << *ptr << std::endl;
    // no need to deallocate the stack allocated pointer variable
}

//Heap allocation
void heapAllocation()
{
    int x = 200;
    int *ptr;
    ptr = new int(x);
    std::cout << *ptr << std::endl;

    // here we need to deallocate the heap allocated pointer variable
    delete ptr; 
    std::cout << *ptr << std::endl; // print deallocated value as zero
}

int main(int argc, char const *argv[])
{
    stackAllocation();
    heapAllocation();
}
Follow me

I work on everything coding and share developer memes