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

朱雀 2022-07-24 05:18 203阅读 0赞

new/delete new[]/delete[]实在是老生常谈了,成对的出现就可以了:

  1. #include <iostream> // std::cout
  2. #include <new> // ::operator new
  3. struct MyClass {
  4. int data[100];
  5. MyClass() {
  6. std::cout << "constructed [" << this << "]\n";}
  7. };
  8. int main () {
  9. std::cout << "1: ";
  10. MyClass * p1 = new MyClass;
  11. // allocates memory by calling: operator new (sizeof(MyClass))
  12. // and then constructs an object at the newly allocated space
  13. std::cout << "2: ";
  14. MyClass * p2 = new (std::nothrow) MyClass;
  15. // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
  16. // and then constructs an object at the newly allocated space
  17. std::cout << "3: ";
  18. new (p2) MyClass;
  19. // does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
  20. // but constructs an object at p2
  21. // Notice though that calling this function directly does not construct an object:
  22. std::cout << "4: ";
  23. MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
  24. // allocates memory by calling: operator new (sizeof(MyClass))
  25. // but does not call MyClass's constructor
  26. delete p1;
  27. delete p2;
  28. delete p3;
  29. return 0;
  30. }
  31. // operator delete[] example
  32. #include <iostream> // std::cout
  33. struct MyClass {
  34. MyClass() {
  35. std::cout <<"MyClass constructed\n";}
  36. ~MyClass() {
  37. std::cout <<"MyClass destroyed\n";}
  38. };
  39. int main () {
  40. MyClass * pt;
  41. pt = new MyClass[3];
  42. delete[] pt;
  43. return 0;
  44. }

我们在写C++程序的时候,非常的小心,很怕会遇到内存泄露的问题。
所以,只记得要delete或delete[]指针,然后赋值为nullptr。

但是往往会为我们的过于谨慎付出代价,当我们delete非new产生的指针会怎样呢?

看代码:

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int *a;
  6. int b = 5;
  7. a = &b;
  8. cout << *a << endl;
  9. delete a;
  10. return 0;
  11. }

上面的程序会崩溃,那下面的呢,居然没问题?

  1. int main()
  2. {
  3. int *a = 0;
  4. delete a;
  5. return 0;
  6. }

原因:

第一段代码会导致不确定的行为,原因就是你delete了非new指针。

第二段代码表面上没问题,是因为delete一个null指针不会有什么危害。

所以,切记
不要delete a pointer which was not allocated dynamically

发表评论

表情:
评论列表 (有 0 条评论,203人围观)

还没有评论,来说两句吧...

相关阅读

    相关 What I do

    Ps:这是19号写的东西,想发表时,却发现上不了网,所以现在才发表,算是记录一下我的生活吧!