how does the new and delete operator work in C++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how does the new and delete operator work in C++?

i am curious to know what happens when the delete operator used in a program? as per my knowledge when i use the delete operator in the program it should de-allocate the memory that was allocated by the new operator. When i executed the following program i got this result. # include <iostream.h> int main( ) { int *ptr; cout << "enter a number "; ptr = new int; cin >> *ptr; cout << "entered value is " << *ptr << endl; delete ptr; cout << "entered value is " << *ptr; return 0; } output: enter a number 10 entered value is 10 entered value is 10 i still get the output even after using the delete operator. why is that happening.

30th Jul 2018, 7:04 AM
santhu jhadav
santhu jhadav - avatar
1 Answer
+ 2
The address of the pointer does not change after you perform delete on it. It simply tells the system that the piece of memory at that address, which was previously reserved, is no longer reserved and is available for re-use. Accessing the object that no longer exists causes undefined behavior. In this case you just observe leftover data in an unused memory. You can use ptr=nullptr; to completely erase the address pointer points at.
30th Jul 2018, 7:22 AM
Steppenwolf
Steppenwolf - avatar