Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting or assigning zero to pointers

In what situations in the codes, should we delete a given pointer and where had we better assign zero to it, instead of deleting?

like image 767
Franky Avatar asked Mar 14 '23 06:03

Franky


2 Answers

In what situations in the codes, should we delete a given pointer and where had we better assign zero to it, instead of deleting?

You delete a pointer if you created it using new. And actually you are deleting an object to which the pointer points, not the pointer itself. Although syntax lets you write delete ptr indeed. But what gets deleted is where ptr points. Not ptr.

Assigning nullptr to the pointer, if you didn't do delete before, doesn't help - you actually lose an address of object where that pointer was pointing and creating a memory leak (of course if there were no other pointers pointing to the original object). e.g. this is bad:

double* pvalue  =  new double;   
..
pvalue = nullptr; // Bad - pointer to original memory is lost now
delete pvalue; // What should I delete?

So if you used new for creating an object you need to delete it before assigning a nullptr to the pointer.

So after deleting it is ok to assign nullptr to the pointer.


All that said you need to consider if you really need dynamic memory allocation (e.g. new) in your code.

like image 103
Giorgi Moniava Avatar answered Mar 15 '23 22:03

Giorgi Moniava


I think that one should delete a pointer when the object it refers to is not needed anymore, after it has been created by using new. And one can assign zero (preferably NULL) to a pointer after it has been deleted to show it is not pointing to something anymore. One can then test afterwards whether or not a pointer equals NULL.

like image 44
Michiel Pater Avatar answered Mar 15 '23 23:03

Michiel Pater