调试死机问题时可根据死机地址快速判断问题出在栈区还是堆区

本文通过一个简单的C++示例程序展示了不当使用new和delete操作符可能导致的内存管理错误,特别是重复释放同一个指针指向的内存所导致的程序崩溃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一段会造成死机的代码及其运行结果:

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
34
35
36
37
#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() {
  cout << "create an object address in stack\n";
  Tree obj(10);
 
  cout << "create an object address in heap\n";
  Tree* t = new Tree(40);
  delete t;
  //t = nullptr;
  delete t;
}

运行结果:

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

create an object address in stack

Tree(), this = 0x7fffdbe5b850

create an object address in heap

Tree(), this = 0x18ab010

~Tree()

~Tree()

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

Aborted (core dumped)


分析:栈空间的对象地址为0x7fffdbe5b850。堆空间的对象地址为0x18ab010。测试环境为64位虚拟机。栈地址的高4字节地址不为0,堆地址的高4字节通常为0。




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







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值