Is deleting a pointer same as freeing a pointer (that deallocates the memory)?
You can't "delete" a pointer variable, only set their value to NULL (or 0).
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.
In short, yes.
But you have to be careful: if you allocate with p = new sometype()
only then should you use delete p
. If you allocate using p = sometype[count]
always use delete [] p
And one more thing: you should never pair malloc/delete
or new/free
.
Yes, delete
is used to deallocate memory and call the destructor for the object involved.
It's common pratice to set pointer to NULL
after deleting it to avoid having invalid pointers around:
Object *o = new Object();
// use object
delete o; // releases memory and call o->~Object()
o = NULL;
When new
and delete
are used with standard C types in C++ source they behave like malloc
and free
.
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
.