我编写了一个递归函数,它使用std :: vector作为临时数据容器。问题是,在某些递归迭代之后,代码会抛出 EXC_BAD_ACCESS 的错误,这似乎与代码无关,因为异常会传播。
如果我在代码printf的处放置任何内容("这很有趣......不是"),我可以产生异常,之前的任何代码似乎都正常执行。
我怀疑我的系统内存不足,但是从活动监视器我可以看到我已经使用了6.5 / 8GB内存,所以情况不是这样吗?
这个EXC_BAD_ACCESS异常可能是什么情况?
void Terrain::CarvePath(int index){
float endElevation = 0.0f;
int actualRowSize = 25 + 1;
int upperRow = index - actualRowSize;
int bottomRow = index + actualRowSize;
if(bottomRow + 1 > 25 * 25 || upperRow - 1 < 0){
return;
}
std::vector<int> surroundingIndices;
// Throws EXC_BAD_ACCESS. If removed throws EXC_BAD_ACCESS
// on the next line ( surroundingIndices.push_back() )
printf("This is funny ... not");
surroundingIndices.push_back(upperRow - 1);
surroundingIndices.push_back(upperRow);
surroundingIndices.push_back(upperRow + 1);
surroundingIndices.push_back(index - 1);
surroundingIndices.push_back(index + 1);
surroundingIndices.push_back(bottomRow - 1);
surroundingIndices.push_back(bottomRow);
surroundingIndices.push_back(bottomRow + 1);
if(lastVertex){
std::remove(std::begin(surroundingIndices),
std::end(surroundingIndices), lastVertex);
}
std::vector<float> surroundingIndicesY;
for (auto &&surroundingIndex : surroundingIndices) {
surroundingIndicesY.push_back
(vertices[surroundingIndex].position.y);
}
std::vector<float>::iterator it;
it = std::min_element(surroundingIndicesY.begin(),
surroundingIndicesY.end());
long vertexToDigIndexTemp =
std::distance(surroundingIndicesY.begin(), it);
int vertexToDigIndex = surroundingIndices[vertexToDigIndexTemp];
vertices[vertexToDigIndex].position.y -= 1.0f;
lastVertex = vertexToDigIndex;
if(vertices[index].position.y == endElevation) return;
CarvePath(vertexToDigIndex);
}
答案 0 :(得分:1)
对我来说就像一个典型的堆栈溢出。由于您的代码是递归的,因此最终可能会在堆栈上返回大量返回地址,这可能导致堆栈空间不足。将代码转换为非递归版本可以解决问题。