对指针调用delete之后要记得把指针赋值为nullptr

简介:

对指针调用delete之后要记得把指针赋值为nullptr

否则,如果这个指针被重复delete,会死机。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using  std::cout;
using  std::endl;
using  std::ostream;
 
class  Tree {
   int  height;
public :
   Tree( int  treeHeight) : height(treeHeight) {
     cout << __func__ <<  "(), this = "  <<  this  << endl;
   }
   ~Tree() { cout <<  "~Tree()\n" ; }
#if 0 
   friend  ostream&
   operator<<(ostream& os,  const  Tree* t) {
     return  os <<  "Tree height is: "
               << t->height << endl;
   }
#else
   friend  ostream&
   operator<<(ostream& os,  const  Tree& t) {
     return  os <<  "Tree height is: "
               << t.height << endl;
   }
#endif
}; 
 
int  main() {
   Tree* t =  new  Tree(40);
   delete  t;
   //t = nullptr;
   delete  t;
}

运行结果:

frank@userver:~/project/test/cpp/new_del$ ./a.out 

Tree(), this = 0x13b2010

~Tree()

~Tree()

*** Error in `./a.out': double free or corruption (fasttop): 0x00000000013b2010 ***

Aborted (core dumped)




      本文转自FrankNie0101 51CTO博客,原文链接:http://blog.51cto.com/frankniefaquan/1936943,如需转载请自行联系原作者





相关文章
|
4月前
|
存储 安全 编译器
【C++专栏】C++入门 | auto关键字、范围for、指针空值nullptr
【C++专栏】C++入门 | auto关键字、范围for、指针空值nullptr
64 0
|
1月前
|
存储 安全 编译器
C++入门 | auto关键字、范围for、指针空值nullptr
C++入门 | auto关键字、范围for、指针空值nullptr
51 4
|
1月前
|
编译器 C语言 C++
【C++关键字】指针空值nullptr(C++11)
【C++关键字】指针空值nullptr(C++11)
|
2月前
|
存储 安全 编译器
【C++入门 四】学习C++内联函数 | auto关键字 | 基于范围的for循环(C++11) | 指针空值nullptr(C++11)
【C++入门 四】学习C++内联函数 | auto关键字 | 基于范围的for循环(C++11) | 指针空值nullptr(C++11)
|
3月前
|
搜索推荐 程序员 C语言
指针赋值与引用传递:C语言的基础知识与实践技巧
指针赋值与引用传递:C语言的基础知识与实践技巧
|
3月前
|
存储 安全 编译器
【C++航海王:追寻罗杰的编程之路】引用、内联、auto关键字、基于范围的for、指针空值nullptr
【C++航海王:追寻罗杰的编程之路】引用、内联、auto关键字、基于范围的for、指针空值nullptr
56 5
|
2月前
|
搜索推荐 程序员 C语言
指针赋值与引用传递:C语言的基础知识与实践技巧
指针赋值与引用传递:C语言的基础知识与实践技巧
|
3月前
|
存储 安全 编译器
C++进阶之路:何为引用、内联函数、auto与指针空值nullptr关键字
C++进阶之路:何为引用、内联函数、auto与指针空值nullptr关键字
35 2
|
9月前
|
存储 安全 编译器
【C++】内联函数、auto关键字、基于范围的for循环、指针空值nullptr
【C++】内联函数、auto关键字、基于范围的for循环、指针空值nullptr
54 0
|
4月前
|
存储 编译器 Linux
【C++】C++入门第二课(函数重载 | 引用 | 内联函数 | auto关键字 | 指针空值nullptr)
【C++】C++入门第二课(函数重载 | 引用 | 内联函数 | auto关键字 | 指针空值nullptr)