[英]valgrind showing memory leaks. how do i stop the leak?
I'm new to valgrind and I ran it with some code I wrote for a quadtree.我是 valgrind 的新手,我用我为四叉树编写的一些代码运行了它。
I've written a function that recursively frees the Nodes from the quadtree:我写了一个函数,递归地从四叉树中释放节点:
void destroyTree (Node* p)
{
if (!p) return;
for (size_t i = 0; i < 4; ++i)
destroyTree(p->child[i]);
free(p);
}
I call that function in the main function:我在主函数中调用该函数:
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;
}
When I run valgrind its showing that I lose some memory.当我运行 valgrind 时,它显示我失去了一些记忆。
The structure is:结构是:
struct qnode {
int level;
double xy[2];
struct qnode *child[4];
};
typedef struct qnode Node;
I call malloc in buildTree:我在 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;
}
How do I stop the leak?我如何阻止泄漏? Is there something wrong with my freeing function or is it somewhere else?我的释放功能有问题还是其他地方有问题?
okay, since noone spotted this, the end of main
reads:好吧,既然没有人发现这一点, main
内容的结尾是:
// print the tree for Gnuplot
writeTree( head );
return 0; // <----------- wooooot!
//destroy tree
destroyTree (head);
return 0;
}
We notice that the 2 last lines are unreacheable because there's a return 0
statement just above this.我们注意到最后两行是无法访问的,因为在这上面有一个return 0
语句。 So the destroyTree
method is never called, which explains the memory leak.所以destroyTree
方法永远不会被调用,这就解释了内存泄漏。
Always enable compiler warnings and read them .始终启用编译器警告并阅读它们。 The control flow is simple enough, every compiler detects dead code here.控制流程很简单,每个编译器都在这里检测到死代码。
That said, even -Wall -Wextra
doesn't work here, the -Wunreachable-code
flag must be added explicitly ( Why does GCC not warn for unreachable code? )也就是说,即使-Wall -Wextra
在这里不起作用,也必须显式添加-Wunreachable-code
标志( 为什么 GCC 不对无法访问的代码发出警告? )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.