Question:
Do I need to nullify a pointer after using the delete
operator? Or does it, unlike the malloc
function, reset the pointer to zero on its own?
int *v = new int(5);
delete v;
v = nullptr;
And what about deleting the pointer in the following code:
(1) int *a = new int[10];
(2) delete [] a;
(3) delete a;
(4) a = nullptr;
Do I need to delete the pointer, as in the third line? If not, then I understand that it is necessary to reset it, as in the fourth?
Answer:
Let's distinguish between a pointer and the data it points to.
The delete
operator operates on the memory pointed to by the pointer. Moreover, if you allocated memory with new
, then you need to free it with delete
. And if with the help of new[...]
, then you need to release it with the help of delete[]
. (You are responsible for this.)
The delete
operator does not change the pointer, but after delete
it points to invalid memory (most likely, this memory will be allocated to someone else for its purposes). It makes sense to assign the nullptr
value to the pointer after delete
on your own, so as not to accidentally use invalid memory. But this is not mandatory and is more of a precaution for you rather than a requirement of the language.
There is only one language requirement: after delete
, you must not access the given memory system by pointer. How you ensure this is entirely up to you.
Yes, and you can't delete an object by a pointer a second time! Because you can’t access remote memory at all (an attempt to delete is also a call). Therefore, line (3)
is wrong on both sides: it is a repeated deletion of memory, which is forbidden, and a deletion without []
, although the memory was allocated with []
.