向量的堆栈溢出错误

Stack Overflow error with Vectors

我有以下导致堆栈溢出的代码。我不知道为什么。 None 我使用的值在异常发生时超出了边界。它被称为 Contour_Depth_Search(0, tmp, 0);其中 tmp=0;

// Global Variables
vector<Vec4i> hierarchy;
vector<vector<Point>> approx_corners, contours;
vector<Point> temp_corner, fiducial_centers;`enter code here`
vector<vector<int>> index_value;
vector<vector<int>> index_depth;

void Contour_Depth_Search(int Indice, int &Nb_Solutions, int depth_level) { 
// Check if current contour is part of a solution
if (approx_corners[Indice].size() == 4) {
    if (!index_depth[Nb_Solutions].empty() && index_depth[Nb_Solutions].back() == depth_level) {
        index_value[Nb_Solutions][index_value[Nb_Solutions].size() - 1] = Indice;
        //index_depth[Nb_Solutions][index_depth[Nb_Solutions].size() - 1] = depth_level;
    }
    else {
        index_value[Nb_Solutions].push_back(Indice);
        index_depth[Nb_Solutions].push_back(depth_level);
    }
}

// I can only search for deeper tree if I found a square in current level or no solutions is started yet (deeper_allowed)
if (hierarchy[Indice][2] != -1) {
    Contour_Depth_Search(hierarchy[Indice][2], Nb_Solutions, depth_level+1);}

// I only go to next node if I cannot find a square in current contour
if (hierarchy[Indice][0] != -1) {
    Contour_Depth_Search(hierarchy[Indice][0], Nb_Solutions, depth_level);}

if (index_value[Nb_Solutions].size() >= 8) {
    Nb_Solutions++;
    index_value.push_back(vector<int>());
    index_depth.push_back(vector<int>());
}
else if (!index_value[Nb_Solutions].empty() && index_depth[Nb_Solutions].back() == depth_level) {
    index_value[Nb_Solutions].pop_back();
    index_depth[Nb_Solutions].pop_back();
}
return;
}

由于堆栈在内存中向下增长,因此必须预先定义堆栈的大小。当 stackPointer < topOfStack 时发生堆栈溢出异常,这意味着在堆栈上放置了太多数据。

就您的代码而言,您似乎在使用递归(Contour_Depth_Search 调用自身)。调用函数时,信息在堆栈上传递。因此,堆栈溢出是未绑定递归的典型症状。我怀疑这是你的问题。如果没有任何输入数据,我真的不可能进一步帮助您,但您可以自己调试它以确定它为什么会如此深入地递归。

我通过将我的 Stack:reserve 分配为 2000000 找到了我的解决方案。我不知道为什么有 3000 个元素时我会遇到堆栈溢出,但是 w/o 更改我的代码,没有快速的解决方案。