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

时间:2019-02-23 20:43:38

标签: c memory-leaks valgrind

我是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;
}

如何阻止泄漏?我的释放功能有问题吗?还是在其他地方?

valgrind memory leak

1 个答案:

答案 0 :(得分:1)

好吧,由于没有人发现这一点,main的结尾为:

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

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

我们注意到最后2行是无法到达的,因为在此上方有一个return 0语句。因此,从未调用destroyTree方法,这说明了内存泄漏。

始终启用并警告编译器警告。控制流程非常简单,每个编译器都会在此处检测到无效代码。

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