您的位置:首页 > 移动开发

What happened if i delete a pointer which was not allocated dynamically?

2016-05-14 12:37 483 查看
new/delete new[]/delete[]实在是老生常谈了,成对的出现就可以了:

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