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.

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 int main()
 4 {
 5     int x;
 6     int *ptr1 = &x;
 7     int *ptr2 = (int *)malloc(sizeof(int));
 8     int *ptr3 = new int;
 9     int *ptr4 = NULL;
10  
11     /* delete Should NOT be used like below because x is allocated on stack frame */
13     delete ptr1;  
14  
15     /* delete Should NOT be used like below because x is allocated using malloc() */
17     delete ptr2;  
18  
19     /* Correct uses of delete */
20     delete ptr3;
21     delete ptr4;
22  
23     getchar();
24     return 0;
25 }

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  10:00:24

原文地址:https://www.cnblogs.com/iloveyouforever/p/3442728.html