![]() |
VOOZH | about |
In C++, memory management is essential to avoid memory leaks, crashes, and undefinable behavior. In this article, we will learn how to properly delete a pointer in C++.
By deleting a pointer, we refer to deleting the memory allocated to the pointer. To delete a pointer in C++ we can use the delete keyword and for arrays allocated with new, use delete[] to deallocate the memory.
After, deleting or deallocating the memory, we should assign the nullptr to the pointer.
For deleting the pointer variable use:
deletepointerName;For deleting the pointer array use:
delete[]arrayPointer;Also, if you have used the malloc() or calloc() function to allocate the memory, then use the free() function for deallocation.
The below example demonstrates how we can delete a pointer properly in C++.
Value of dynamicInt: 42
Note: Undefined behavior occurs when attempting to remove a single point more than one time. So, before deleting the pointer, always check that it is not null .