Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using 'delete' before reassigning value for pointer is redudant?

Should I use ‘delete’ in the following example?

int main(){
T object;
T* pointer = new T[4];
delete[] pointer; // this line is redudant? or error?
pointer = &object;
}

I’m asking Chat GPT this same question and it says: "the line delete is redudant and may lead to undefined behaviour, because when you re-assign the pointer, the data on heap is automatically deallocated". But i have a doubt about this. So should I use ‘delete’ there?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"the line delete is redudant and may lead to undefined behaviour, because when you re-assign the pointer, the data on heap is automatically deallocated"

This is utter nonsense.

What you create via new you must eventually be deleted via delete (and delete [] for what has been allocated via new []). The line does not lead to undefined behavior. It is also not redundant, because if you do not delete the array you have a memory leak. Reassinging the pointer does not deallocate the memory it was pointing to.

It should be noted that you should not use new in the first place. Raw owning pointers are dangerous and will lead to problems. Use std::vector, other containers, and smart pointers for dynamic memory managment, but don’t do it manually.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading