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

标签 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

最佳答案

好的,因为没有人发现这一点,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? )

关于c - valgrind 显示内存泄漏。我该如何阻止泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54846024/

相关文章:

c++ - 如何在 Lua 代码中扩展 SWIG 的用户数据?

c - recv() 接收部分消息的套接字编程问题

c - 即使在使用 free() 之后,Valgrind 也会报告丢失的字节

ubuntu - 对文件的 Valgrind 权限被拒绝

c++ - 我怎样才能故意用未初始化的数据初始化一个变量,以便 valgrind 将该变量视为未初始化的?

创建新变量并进行嵌套循环

c++ - gstreamer:如何更改网络摄像头的输入/输出分辨率?

c++ - 使用 opencv : VideoCapture 内存泄漏

java - 这会导致内存泄漏吗

ios - PKCS12_newpass 中的内存泄漏