valgrind 显示内存泄漏。我该如何阻止泄漏?

valgrind showing memory leaks. how do i stop the leak?

我是 valgrind 的新手,我 运行 使用我为四叉树编写的一些代码。

我写了一个递归地从四叉树中释放节点的函数:

void destroyTree (Node* p)
{
    if (!p) return;

    for (size_t i = 0; i < 4; ++i)
        destroyTree(p->child[i]);

    free(p);
}

我在主函数中调用了那个函数:

int main( int argc, char **argv ) {

  Node *head;

  // make the head node
  head = makeNode( 0.0,0.0, 0 );

  // make a tree
  makeChildren( head );
  makeChildren( head->child[0] );
  makeChildren( head->child[1] );
  makeChildren( head->child[2] );
  makeChildren( head->child[3] );

  // print the tree for Gnuplot
    writeTree( head );
  return 0;

  //destroy tree
  destroyTree (head);
  return 0;
}

当我 运行 valgrind 它显示我失去了一些记忆。

结构是:

struct qnode {
  int level;
  double xy[2];
  struct qnode *child[4];
};
typedef struct qnode Node;

我在buildTree中调用malloc:

Node *makeNode( double x, double y, int level ) {

  int i;

  Node *node = (Node *)malloc(sizeof(Node));

  node->level = level;

  node->xy[0] = x;
  node->xy[1] = y;

  for( i=0;i<4;++i )
    node->child[i] = NULL;

  return node;
}

如何阻止泄漏?是我的释放函数有问题还是其他地方?

好的,因为没有人发现这一点,所以 main 的结尾是:

  // print the tree for Gnuplot
    writeTree( head );
  return 0;    // <----------- wooooot!

  //destroy tree
  destroyTree (head);
  return 0;
}

我们注意到最后两行无法访问,因为在其上方有一个 return 0 语句。所以 destroyTree 方法永远不会被调用,这就解释了内存泄漏。

始终启用编译器警告并阅读它们。控制流足够简单,每个编译器都会在这里检测死代码。

也就是说,即使 -Wall -Wextra 在这里不起作用,必须明确添加 -Wunreachable-code 标志 (Why does GCC not warn for unreachable code?)