std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误

std::vector using back(), pop_back(), push_back(), get 'double free or corruption' error

本文关键字:back double free corruption 错误 or vector std push 得到 using      更新时间:2023-10-16

我有以下代码:

struct branchInfo{
Quaternion r;
Vector3 p;
std::vector<Vector3> branchPoints;
};
std::vector<Vector3> LSystem::Turtle(){
std::vector<branchInfo> b;
// The axiom should always start with a '[' at the start and a ']' at the end
for(unsigned int i = 0; i < axiom.length(); i++) {
char c = axiom[i];
if (c == '[') {
branchInfo temp;
temp.r = rotationQuat;
temp.p = position;
temp.branchPoints.push_back(position);
b.push_back(temp);
} else if (c == ']') {
branchInfo temp = b.back();
rotationQuat = temp.r;
position = temp.p;
branches.push_back(temp.branchPoints);
b.pop_back();
} else {
// Evaluate the character and move the turtle
// F = move forward according to pitched, rolled, and yawed axis
// f = move backward according to pitched, rolled, and yawed axis
// p = pitch -45 degrees
// P = pitch +45 degrees
// r = roll -45 degrees
// R = Roll +45 degrees
// y = yaw -45 degrees
// Y = yaw +45 degrees
// [ = start new branch
// ] = end new branch
switch(c) {
case 'f':
b.back().branchPoints.push_back(Forward(-1.5f));
break;
case 'F':
b.back().branchPoints.push_back(Forward(1.5f));
break;
case 'p':
Pitch(-angle);
break;
case 'P':
Pitch(angle);
break;
case 'r':
Roll(-angle);
break;
case 'R':
Roll(angle);
break;
case 'y':
Yaw(-angle);
break;
case 'Y':
Yaw(angle);
break;
}
}
}
}

这段代码的重点是计算将遵循的公理字符串。这是一个L系统,L系统的一部分要点是分支,当有一个"["字符时就会发生这种情况,这意味着旋转和位置被保存并在以后使用。例如,如果我的 L 系统类包含字符串"[PPPPrrFp[[X]PX]pXRR]"我将收到以下错误:*** Error in /home/user/program/dist/Debug/GNU-Linux/world': double free or corruption (fasttop): 0x0000000003f43240 ***

我知道逐步完成这个程序并不容易,我不希望有人这样做。我只是想知道是否很容易看出该程序有什么问题。我知道该错误可能与使用某些 std::vector 方法/函数有关,但我不明白它为什么或如何导致它。

此外,它不一致。有时程序会顺利运行,有时它会因我提到的错误而崩溃。

偏航、俯仰和滚动功能应该无关紧要。

从我用谷歌搜索的内容来看,我只能在处理具有构造函数、析构函数的类以及删除数组等时找到此错误的示例。

感谢您的任何帮助!我希望正在发生的事情是显而易见的,并且不会花费太多时间。如果看起来确实需要太长时间,请不要打扰。再次感谢。

编辑:为了更容易理解函数中发生的事情,我将对该函数进行分步解释: 从公理字符串的索引 0 开始并检查它是否启动一个新分支 ('['(,如果它开始了,那么推送/保存 3D 矢量 pos 和 rot ->如果当前字符不是 '[' 或 ']',则移动 pos 或旋转 ->如果分支结束 (']'( 从上次保存的 pos 和腐烂中复苏,并弹出堆栈的顶部 ->继续为字符串中的每个字符继续前进。

以防未来的人遇到这个问题。我做错的是没有在我的函数中返回任何内容,即使我为函数指定了一个非 void 返回类型。将返回类型更改为void解决了我的问题。