Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does deleting a pointer mean?

Is deleting a pointer same as freeing a pointer (that allocates the memory)?

like image 660
Ashish Yadav Avatar asked Mar 15 '10 18:03

Ashish Yadav


People also ask

What does deleting a pointer do?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. New operator is used for dynamic memory allocation which puts variables on heap memory. Which means Delete operator deallocates memory from heap.

What does delete pointer do in C++?

It destroys the memory at the runtime. It should only be used either for the pointers pointing to the memory allocated using the new operator or for a NULL pointer. It should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

Does deleting a pointer delete the object?

Deleting a pointer, or deleting an object (by passing a pointer to that object to delete )? The pointer to that inner object will be deleted, but the object itself won't be.

Can you use a pointer after deleting it?

Yes, it's totally fine to reuse a pointer to store a new memory address after deleting the previous memory it pointed to. Just be careful not to dereference the old memory address which is still stored in the pointer. In your code snippet that's not a problem though.


2 Answers

You can't "delete" a pointer variable

Sure you can ;-)

int** p = new int*(new int(42));
delete *p;
delete p; // <--- deletes a pointer

But seriously, delete should really be called delete_what_the_following_pointer_points_to.

like image 87
fredoverflow Avatar answered Nov 15 '22 20:11

fredoverflow


Deleting a pointer (or deleting what it points to, alternatively) means

delete p;
delete[] p; // for arrays

p was allocated prior to that statement like

p = new type;

It may also refer to using other ways of dynamic memory management, like free

free(p);

which was previously allocated using malloc or calloc

p = malloc(size);

The latter is more often referred to as "freeing", while the former is more often called "deleting". delete is used for classes with a destructor since delete will call the destructor in addition to freeing the memory. free (and malloc, calloc etc) is used for basic types, but in C++ new and delete can be used for them likewise, so there isn't much reason to use malloc in C++, except for compatibility reasons.

like image 40
Johannes Schaub - litb Avatar answered Nov 15 '22 19:11

Johannes Schaub - litb