What happened if i delete a pointer which was not allocated dynamically?
2016-05-14 12:37
483 查看
new/delete new[]/delete[]实在是老生常谈了,成对的出现就可以了:
我们在写C++程序的时候,非常的小心,很怕会遇到内存泄露的问题。
所以,只记得要delete或delete[]指针,然后赋值为nullptr。
但是往往会为我们的过于谨慎付出代价,当我们delete非new产生的指针会怎样呢?
看代码:
上面的程序会崩溃,那下面的呢,居然没问题?
原因:
第一段代码会导致不确定的行为,原因就是你delete了非new指针。
第二段代码表面上没问题,是因为delete一个null指针不会有什么危害。
所以,切记
不要delete a pointer which was not allocated dynamically
#include <iostream> // std::cout #include <new> // ::operator new struct MyClass { int data[100]; MyClass() {std::cout << "constructed [" << this << "]\n";} }; int main () { std::cout << "1: "; MyClass * p1 = new MyClass; // allocates memory by calling: operator new (sizeof(MyClass)) // and then constructs an object at the newly allocated space std::cout << "2: "; MyClass * p2 = new (std::nothrow) MyClass; // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow) // and then constructs an object at the newly allocated space std::cout << "3: "; new (p2) MyClass; // does not allocate memory -- calls: operator new (sizeof(MyClass),p2) // but constructs an object at p2 // Notice though that calling this function directly does not construct an object: std::cout << "4: "; MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass)); // allocates memory by calling: operator new (sizeof(MyClass)) // but does not call MyClass's constructor delete p1; delete p2; delete p3; return 0; }
// operator delete[] example #include <iostream> // std::cout struct MyClass { MyClass() {std::cout <<"MyClass constructed\n";} ~MyClass() {std::cout <<"MyClass destroyed\n";} }; int main () { MyClass * pt; pt = new MyClass[3]; delete[] pt; return 0; }
我们在写C++程序的时候,非常的小心,很怕会遇到内存泄露的问题。
所以,只记得要delete或delete[]指针,然后赋值为nullptr。
但是往往会为我们的过于谨慎付出代价,当我们delete非new产生的指针会怎样呢?
看代码:
#include <iostream> using namespace std; int main() { int *a; int b = 5; a = &b; cout << *a << endl; delete a; return 0; }
上面的程序会崩溃,那下面的呢,居然没问题?
int main() { int *a = 0; delete a; return 0; }
原因:
第一段代码会导致不确定的行为,原因就是你delete了非new指针。
第二段代码表面上没问题,是因为delete一个null指针不会有什么危害。
所以,切记
不要delete a pointer which was not allocated dynamically
相关文章推荐
- iOS开发——Cocoapods的安装和使用
- 团队作业之旅游行业APP分析
- Android中使用Gson解析JSON数据的方法
- Android Development Environment ADT-BUNDLE android-studio SDK ADT Download
- Android高阶之AS如何打.aar包,并应用
- Android Studio 快捷键 for Mac OS X
- Android SimpleAdapter传入Bitmap
- Android BItmap和String互转
- Android aapt实现资源分区(补充携程aapt源码)
- Android文件递归遍历
- mapping 详解3(Meta-Fields)
- Android获取内存卡MP3信息
- 关于CoreImage人脸检测
- Android基础知识点汇总
- unity 计算两点角度
- cordova新建android工程
- iOS开发——静态库的导入和头文件路径的设置
- Android开发艺术探索 第十章 学习
- unity 计算两点的距离
- 关于android程序中使用bitmap放大功能时的OOM问题解决方法