使用多重链接树解决内存问题

时间:2018-03-23 11:03:28

标签: c++

我有一棵树,每个节点有六个子节点,也有一个指向它父节点的指针。结构看起来像这样:

  login(email, password){
    const request = new XMLHttpRequest()
    const uri = leadingURI + "adminapi/users/login"
    console.log(uri);
    request.open("POST", uri)
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    request.onload = () => {
      if ( request.status === 201 ){
        console.log("login successful!");
        console.log(request.responseText)
        // this.setState({userI})
        return true
      } else {
        console.log("Failed login : ", request.status)
        console.log(request.responseText);
        return false
      }
    }
    let dataToSend = {}
    dataToSend["email"] = email
    dataToSend["password"] = password
    console.log(JSON.stringify(dataToSend));
    request.send(JSON.stringify(dataToSend))
  }

根节点初始化为:

struct node
{
  float value;
  int wins;
  int games;
  int visited;
  int colour;

  node *prev;

  node *p[6];
};

扩展功能如下所示:

root = new node;
root -> value   = 0.0;
root -> wins    = 0;
root -> games   = 0;
root -> visited = 0;
root -> colour  = c; //root node has same colour as opponent

root -> prev = NULL; //can use this to find root.

for(int i=0;i<6;i++)
  root -> p[i] = NULL;

我认为我的主要问题是在我的函数中释放看起来像这样的内存:

void expansion(int column, node *leaf)
{
  node *child = new node;
  child -> value   = 0.0;
  child -> wins    = 0;
  child -> games   = 0;
  child -> visited = 0;

  if(leaf -> colour == 1)
    child -> colour  = -1;
  else
    child -> colour  = 1;

  child -> prev = leaf;

  for(int i=0;i<6;i++)
    child -> p[i] = NULL;

  leaf -> p[column] = child;
}

基本上我试图扩展一个函数来删除我的函数的二叉树,我需要删除所有六个孩子。

2 个答案:

答案 0 :(得分:2)

  

delete leaf -> prev;这似乎不对。为什么还要删除上一个节点? - 轨道中的轻盈竞赛

正确 - 想象只有两个节点rootroot->p[0]会发生什么:

destroy_tree(root)
{
    destroy_tree(p[0])
    {
        delete leaf->prev; // which is root!
        delete leaf;
     }
     delete leaf->prev; // nullptr anyway (*)
     delete leaf;  //// root; ALREADY deleted!!! ////
}

(*)prev 作为空指针 - 如果它还存在的话!但是当你已经删除了leaf(也就是root)时,你实际上是在取消引用一个悬空指针(未定义的行为)!然后立即尝试通过这个悬空指针删除 - 再次未定义的行为......

valgrind是一个非常好但不完美的工具。它发现你显然没有删除指针(prev)指向的对象,它发现它是潜在的内存泄漏。显然,它不知道prev指针的对象是通过另一个指针可以访问的......

答案 1 :(得分:1)

假设您的节点LP有两个子节点LC1,LC2:

LP-&gt; p [0] == LC1,

LP-> p [1] == LC2,

LC1-&gt; prev == LP,

LC2-&gt; prev == LP

然后致电

$content = json_decode($response, true);

展开

destroy_tree(LP)