Is deleting a pointer same as freeing a pointer (that allocates the memory)?
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.
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With