jjepsuomi
jjepsuomi

Reputation: 4373

Difference between deallocating a single variable or array in C++

I'm studying about new and new[] from learncpp and there is one small detail in the site, which isn't clear enough for me. The following picture will explain my question:

enter image description here

So do we have to set the array-pointer also to 0 after we have deallocated it like in the single variable case? Is this a requirement or is the procedure different with delete and delete[]?

Thnx for any help! =)

Upvotes: 1

Views: 340

Answers (2)

AdR
AdR

Reputation: 115

It very depends what you are planning to do further in the code. Setting a pointer to to NULL/nullptr after deleting the object it used to point to (regardless whether it is a pointer pointing to the array or to the singular variable), is done purely to mark a pointer as deallocated ,so you can easily check if that pointer is still 'active' or not by :

if (pnArray != nullptr) 
{
  // now it is safe to dereference the pointer
}

If the double deletion occurs in the code (shouldn't be the case), calling a delete operator on nullptr will not crash the program (double deletion may bring significant amount of pain: it may crash the application, corrupt the heap, make some changes to the objects already allocated on the heap..) :

delete pnValue;
pnValue = nullptr;
....
delete pnValue; // safe to delete ( still it's not no-op )

You don't need to set the pointers to nullptr-s if you delete the class members in it's destructor for instance (as that pointers will not be used anymore).

These are the raw pointers, maybe have a look also at the smart pointers, which are in general much safer option

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119174

You don't have to set a pointer to zero after any deallocation. This is simply done to make it easy to tell that the pointer no longer points to anything.

Upvotes: 4

Related Questions