delete and free() in C++
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.
Recommended Posts:
- How to deallocate memory without using free() in C?
- How does free() know the size of memory to be deallocated?
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- "delete this" in C++
- delete() in C++
- C++ | new and delete | Question 5
- C++ | new and delete | Question 4
- C++ | new and delete | Question 3
- C++ | new and delete | Question 2
- C++ | new and delete | Question 1
- How to delete last element from a map in C++
- How to delete last element from a List in C++ STL
- How to delete an element from the Set by passing its value in C++
- Delete elements in C++ STL list
- C program to delete a file



