Reputation: 359
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?
Upvotes: 2
Views: 321
Reputation: 129374
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.
Upvotes: 6
Reputation: 42083
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?
Upvotes: 4
Reputation: 726589
No, it does not mean setting the memory to any particular value+. The memory simply gets back into the heap of values that can be reused. The runtime often use several bytes of the returned chunk to store "bookkeeping" information, but they do not set the entire chunk to a particular value. Once a memory chunk is reused, it is your program that sets its new values.
Upvotes: 3