Write two different ways to delete the memory correctly

Question

Write two different ways to delete the memory correctly at the indicated spot
int* X= new int;
int* Y = new int;
*X =2;
*y =6;
int* temp;
temp = X;
X=Y;
Y = temp;
//delete memory here

Summary

In this question, we have to Write two different ways to delete the memory. there are in total two ways of deleting the memory which we will see.

Explanation

In every programming language when we write a program variables holds a memory. So in C++ when we have to Create a variable computer will allocate a memory to it. To allocate the memory pointer we use a keyword ‘new’. So as we allocate a memory we can also delete it if we want. To delete a memory we just need to add a ‘delete’ keyword.

So to delete we have a syntax i.e.
int *p= new int;
//statements
delete p;

There are in total two ways of deleting or destroying the element.
⦁ Either delete the pointer pointing to the value directly.
⦁ Or set the pointer to NULL and then delete that pointer.

Code

#include<iostream>
using namespace std;

int main()
{
    int *x= new int;
    int *y= new int;
    
    *x=8;
    *y=4;
    
    int *temp;
    temp=x;
    x=y;
    y=temp;
    
    delete x;	//delete pointer directly pointing some value by delete keyword
    
    y=NULL;
    delete y;	//delete pointer pointing NULL by keyword null
    cout<<"Successfully Deleted ";

return 0;
}

Output

 

Also read, make a while loop that asks for a person’s age and only accepts an age between 1 and 100.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *