C++递归访问同类型类成员指针时程序崩溃问题求助
递归程序中访问Data类child指针崩溃的问题解决
问题根源
你的程序崩溃是因为指针指向了已销毁的局部变量,形成野指针:
- 在
typecheck函数中,childData是栈上的局部变量,函数执行完毕返回时,该变量占用的内存会被操作系统回收。 - 你将
child指针指向&childData并赋值给data.child,此时data.child就变成了野指针。第一次调用readTuples时childData尚未销毁,所以能正常输出;但后续函数中再访问该指针时,对应的内存已被释放或被其他数据覆盖,必然导致崩溃、输出乱码。
解决方案
方案一:使用动态分配的对象存储childData
通过动态分配内存,确保childData的内存不会在函数返回时被释放:
Data typecheck(Data data) { Data* child = new Data(); // 用动态分配存储返回的Data对象 Data* childData = new Data(statementList->typecheck(*child)); data.child = childData; data.child->readTuples(); return data; }
注意:需要在Data类的析构函数中手动释放child的内存,避免内存泄漏:
class Data { public: vector<tuple<string, string, string>> myTuple; Data *child; void readTuples(){ for (int i = 0; i < myTuple.size(); i++) { std::cout << "ID: " << get<0>(myTuple[i]) << "\tTYPE: " << get<1>(myTuple[i]) << "\tVALUE: " << get<2>(myTuple[i]) << "\n"; } } ~Data() { delete child; // 析构时释放child指针指向的内存 } };
方案二:调整函数返回值为指针或引用
如果可以修改statementList->typecheck的返回类型,让它直接返回动态分配的对象指针:
Data typecheck(Data data) { // 假设statementList->typecheck现在返回Data*,内部完成new Data并初始化逻辑 Data* childData = statementList->typecheck(); data.child = childData; data.child->readTuples(); return data; }
同样需要在Data类的析构函数中添加delete child;来释放内存。
方案三:使用智能指针自动管理内存
避免裸指针的内存管理风险,改用std::unique_ptr自动管理内存:
#include <memory> // 引入智能指针头文件 class Data { public: vector<tuple<string, string, string>> myTuple; std::unique_ptr<Data> child; // 替换裸指针为智能指针 void readTuples(){ for (int i = 0; i < myTuple.size(); i++) { std::cout << "ID: " << get<0>(myTuple[i]) << "\tTYPE: " << get<1>(myTuple[i]) << "\tVALUE: " << get<2>(myTuple[i]) << "\n"; } } }; Data typecheck(Data data) { auto child = std::make_unique<Data>(); Data childData = statementList->typecheck(*child); data.child = std::make_unique<Data>(childData); data.child->readTuples(); return data; }
智能指针会在对象生命周期结束时自动释放内存,无需手动调用delete,彻底避免野指针和内存泄漏问题。
内容的提问来源于stack exchange,提问作者CodingDaveS
相关产品推荐
相关产品推荐

