为什么下面的删除不正确?
ip= static_cast<int*>malloc(sizeof(int));
*ip= 12;
. . .
delete ip; // wrong!
为什么下面的删除不正确?
ip= static_cast<int*>malloc(sizeof(int));
*ip= 12;
. . .
delete ip; // wrong!
您应该要求free()
释放使用malloc()
.
运算符delete
仅用于.new
所以,要么
ip= static_cast<int*>malloc(sizeof(int));
*ip= 12;
. . .
free(ip);
或者
ip= new int;
*ip= 12;
. . .
delete ip;
ip = 0;
请注意,在释放已删除的指针后将其无效是一个好主意,这样将来任何错误地取消引用它的尝试都将保证失败,并使错误更容易定位。
malloc
应该与 配对free
,并且new
应该与 配对delete
。delete
会做一些不会做的额外事情free
(例如调用析构函数),因此使用它来释放分配的内存malloc
可能很糟糕。