double free or corruption (fasttop)问题解决
作为一个C++小白,看了诸路大神在CSDN上有关该问题的解析,发现只看懂了“出现这种问题只有两个原因:一是内存重复释放,看程序中是否释放了两次空间;二是内存越界”。因此我只能用传统的debug方法一个个溯源找问题。
问题背景是我在生成并delete一个constraint tree的时候。一开始问题显示出现在delete节点那一行,而问题是在我将一个定长数组改为vector后出现的。
原定长array代码
CBSNode* child[2] = { new CBSNode(), new CBSNode() };
curr->conflict = chooseConflict(*curr);
修改后的不定长vector代码
curr->conflict = chooseConflict(*curr);
int num_of_child;
if(curr->conflict->type != conflict_type::DUPLICATE)
num_of_child = 2;
else
num_of_child = num_of_agents_;
vector<CBSNode*> child(num_of_child, new CBSNode());
在delete的位置设断点发现两个子节点的地址是一样的,因此delete两次会出现问题。因此我不断设断点,查找究竟是哪里开始,子节点地址相同,最后翻阅C++ primer plus发现了是自己写vector的时候出了问题。
vector v(n, val) 意味着 v包含了n个重复的元素,每个元素的值都是val。
因此我将上述代码改成了
curr->conflict = chooseConflict(*curr);
int num_of_child;
if(curr->conflict->type != conflict_type::DUPLICATE)
num_of_child = 2;
else
num_of_child = num_of_agents_;
vector<CBSNode*> child(num_of_child);
然后在需要用到childnode[i]的时候,令childnode[i]=new CBSNode();
至此,问题解决