gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:43 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com