delete in c++

Hi,

do we need to set NULL to class pointer after delete it.

myClass *mC = new MyClass (a, c).

.
.
.
.
delete mC; <--- is this enough or need to set it NULL.

-nandlal

My understanding is this: delete() frees the memory space allocated already. However, if you do not reset the pointer to NULL, it will continue to point to a freed memory block (which may subsequently be allocated for some other uses) and lead to segmentation fault or mysterious behaviour with unexpected value if you happen to access that pointer. To safeguard, reset the pointer to NULL as soon as the memory location is freed.

I guess it is used for safeguarding from re-deleting some pointer that was already deleted in the past and for knowing which pointer references real object and which one is not. For example if you have some kind of a pool (array of pointers) of objects of some type that you manage manually (allocating new objects, deallocating old ones), you have to know, whether some particular pointer in the pool is actually valid. So when you deallocate an object from the pool, you set its pointer to NULL and then you know that this pointer may be used again in the future. In case of freeing the whole pool you have to delete only those pointers that are not NULL.

On my system (Ubuntu Linux 6.06) there is no difference in referencing NULLed and invalid pointer, I get segmentation fault in both cases.

thanks a lot for highlighting on my query.

As nutrino said After deleting the the class memory pointer becomes dangling pointer and there are many consequences of that and might affect to crash ur program also

I hope below article will help you

Dangling pointers