c – stl map <>中的分段错误
发布时间:2020-12-16 10:26:45 所属栏目:百科 来源:网络整理
导读:我不是很擅长c,但我必须测试一个基于声誉的系统.下面给出了一个代码片段,当我在ubuntu系统上运行它时,它给出了段错误.正如我在评论中写的那样,两个函数“tackleFirstHandInfo()”和“updateReputation()”分别正确运行但是当我从另一个函数调用一个函数时它
我不是很擅长c,但我必须测试一个基于声誉的系统.下面给出了一个代码片段,当我在ubuntu系统上运行它时,它给出了段错误.正如我在评论中写的那样,两个函数“tackleFirstHandInfo()”和“updateReputation()”分别正确运行但是当我从另一个函数调用一个函数时它会崩溃.任何帮助将不胜感激,提前感谢.代码如下:
"ex.h" #ifndef _ex_h #define _ex_h #include "iostream" #include <map> #define FADING 0.9 enum Behaviour {FORWARDING,NOTFORWARDING}; class Rating { private: double reputation; public: Rating() { reputation = 5.0; } Rating(double rep) {reputation = rep;} ~Rating() {} double getRep() { return reputation; } void updateRep(Behaviour behaviour) { if (behaviour == FORWARDING) reputation = reputation + 1; else reputation = reputation - 1; } }; #endif "ex.cc" #include <map> #include <string> #include <iostream> #include "ex.h" using namespace std; typedef map<int,Rating*> ratingTable; class RepSys { private: ratingTable repTable; map<int,Rating*> fHandInfo; Rating* rating; public: RepSys(){} ~RepSys(){} void tackleFirstHandInfo(int address,Behaviour behaviour) /* This Function and the function below individually run correctly */ { map<int,Rating*>::iterator it; it=fHandInfo.find(address); if (it == fHandInfo.end()) { cout << "Adding New Entry for (fHandInfo) "<< address <<endl; rating = new Rating(); fHandInfo[address] = rating; } (it->second)->updateRep(behaviour); cout<<"First Hand Reputation of "<<address<<"t is ="<< (it->second)->getRep()<<endl; updateReputation(address,behaviour); // This causes SegFault !!!! return; } void updateReputation(int address,Behaviour behaviour) { map<int,Rating*>::iterator it; it = repTable.find(address); if (it == repTable.end()) { cout << "Adding New Entry for (repTable) "<< address <<endl; rating = new Rating(); repTable[address] = rating; } (it->second)->updateRep(behaviour); cout<<"Reputation of "<<address<<"t is ="<< (it->second)->getRep()<<endl; } }; int main() { int address; RepSys repsys; while (address != 0) { cout << "Addressn"; cin >> address; repsys.tackleFirstHandInfo(address,FORWARDING); } return 0; } 解决方法
您在两个函数中都遇到了一个主要问题,它是:
if (it == fHandInfo.end()){ // Some code that doesn't alter 'it' } (it->second)->updateRep(behaviour); 如果它确实指向最后,则它不是可解除引用的,因此它 – >第二个具有未定义的行为.如果要插入某些内容并希望它指向它,则必须重做查找或使用返回迭代器(或包含迭代器的对)的insert方法,并将其重新分配给返回值的正确部分. 编辑 还有几点: class RepSys { private: ratingTable repTable; map<int,Rating*> fHandInfo; Rating* rating; 您已经将typedefed ratingTable设置为map< int,Rating *>.将typedef用于一个类变量而不是另一个变量似乎有点不一致. rating是一个类变量,但您似乎只将它用作两个函数中的临时持有者.如果这是您的预期用途,最好在两个函数中使用局部变量. 您永远不会删除放置在地图中的Rating对象.如果地图应该拥有Rating对象,那么从对象生命周期/内存管理的角度来看,使用std :: map< int,Rating>会更容易.这样您就不必进行任何手动删除.似乎评级不是基本调用,它是一个值类. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |