In C++, delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.
#include<stdio.h> #include<stdlib.h> int main() { int x; int *ptr1 = &x; int *ptr2 = (int *)malloc(sizeof(int)); int *ptr3 = new int; int *ptr4 = NULL; /* delete Should NOT be used like below because x is allocated on stack frame */ delete ptr1; /* delete Should NOT be used like below because x is allocated using malloc() */ delete ptr2; /* Correct uses of delete */ delete ptr3; delete ptr4; getchar(); return 0; } |
chevron_right
filter_none
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- new vs malloc() and free() vs delete in C++
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- What happens if we mix new and free in C++?
- How does free() know the size of memory to be deallocated?
- How to deallocate memory without using free() in C?
- what happens when you don't free memory after using malloc()
- Queries to insert, delete one occurrence of a number and print the least and most frequent element
- new and delete operators in C++ for dynamic memory
- C++ | new and delete | Question 2
- C++ | new and delete | Question 3
- C++ | new and delete | Question 4
- C++ | new and delete | Question 5
- Different ways to delete elements in std::map (erase() and clear())
- Overloading New and Delete operator in c++
- "delete this" in C++
- Delete elements in C++ STL list
- C program to delete a file
- Program to delete a line given the line number from a file
- delete() in C++
- How to delete last element from a map in C++

