您的位置:首页 > 编程语言 > C语言/C++

delete() and free() in C++

2013-11-26 10:01 141 查看
  

  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;
}


  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: