Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What means 'destroying' memory by delete operator in C++?

Tags:

c++

memory

I would like to know what happens to memory that is destroyed by "delete" operator in C++. Is 'destroying' memory in such way means setting given pieces of memory to 0 or something else?

like image 481
Zygmuntix Avatar asked Nov 20 '25 17:11

Zygmuntix


2 Answers

It is destroying (as in calling the relevant destructor for) the object instance passed to delete, and then "frees" the memory so that it can be used for other purposes.

The C++ standard states nothing about what the contents of the memory will be after delete, and it is certainly not guaranteed to be zero or any other value - nor is it guaranteed that it is NOT zero - it may be zerod, it may retain all the values it had before, or some parts of it may be altered and others remain the same.

The goal of C and C++ as languages is to "only do the minimum necessary", so a typical memory free will not overwrite the "old" memory.

You could of course use code in the destructor to set the memory to zero before it is freed.

Since you are not supposed to use memory after it has been deleted, it shouldn't really matter.

like image 193
Mats Petersson Avatar answered Nov 23 '25 05:11

Mats Petersson


delete just releases the memory (previously allocated by new) and in case that some object has been stored within this memory, the destructor is also invoked.

delete doesn't change the value of the pointer and neither it modifies the memory that has been released, thus you'll notice that many people are used to assign NULL to this pointer after calling delete just to make sure they will not end up with dereferencing invalid (dangling) pointer, which produces undefined behavior.

Worth to have a look at: Is it good practice to NULL a pointer after deleting it?

like image 22
LihO Avatar answered Nov 23 '25 06:11

LihO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!