当我尝试构建八叉树结构时堆栈溢出

Stack overflow when I try to build an octree structure

本文关键字:结构 堆栈 栈溢出 八叉树 构建      更新时间:2023-10-16

我想建立一个n维树。我使用vector来存储每个节点的子节点。我写的代码给出了"堆栈溢出错误",我不知道为什么,我确实使用了new.如果有人能告诉我哪里出错了,我将不胜感激。

class Node
{
public:
  int q_number;
  int layer;
  int value;
  vector<Node*> n_list;
  Node(int n):q_number(n),n_list(n) //initialize node vector
  {
  }
};
Node* buildtree(int n,int depth)
{
  Node * node = new Node(depth);
  if(n==depth-1)
  {
    for(int i = 0; i<depth;i++)
    {
      node->n_list[i] = NULL;
      node->n_list[i]->value = i;
      node->n_list[i]->layer = depth-1;
    }
  }
  else
  { 
    for (int i =0;i<depth;i++)
    {               
      node->n_list[i] = buildtree(n++,depth);// span the tree recursively           
      node->n_list[i]->value = i;
      node->n_list[i]->layer = n;   // the layer value
    }
  }
  return node;
}
int main()
{
  Node * tree = buildtree(0,8); // build an octree
}

正如 Dolda2000 所注意到的,在递归调用buildtree时,您正在递n。因此,n在其旧值(未更改(传递给函数后递增。因此,您有无限的buildtree(0,8);调用堆栈,这自然会导致堆栈溢出。

递增 - buildtree(++n,depth); - 可以解决堆栈溢出的问题,但在这种情况下这不是您想要的,因为您在递归调用后使用n。正如我理解您的意图,您不希望n的值在递归调用后发生变化。

在您的情况下,解决方案只是:

buildtree(n+1,depth);

您的代码中还有另一个问题:

    node->n_list[i] = NULL; // ok, the pointer is NULL now
    node->n_list[i]->value = i; // trying to dereference a NULL pointer => error
    node->n_list[i]->layer = depth-1;

您需要在此处使用new Node(...),或者将向量的值类型从 Node* 更改为 Node ,...或者确保在取消引用指针之前正确设置指针。

附言并确保n <= depth-1 - 通过断言,或在代码中包含注释,至少以避免以后进行大量调试。