在我的程序中,我在链表中声明了一些节点:
node_t* newSymbol = malloc(sizeof(node_t));
newSymbol->symbol.name = strdup(name); //name is a (const) char* that is a parameter to function I'm in.
newSymbol->symbol.addr = addr;
我使用 strdup 是因为像这样直接将符号名称分配给参数:
newSymbol->symbol.name = name;
说当我丢弃传递的参数的 const 属性时出现错误。
问题:我在另一个堆栈溢出中读到,您需要释放由 strdup 创建的内存。当我的程序退出时,我对每个节点执行以下操作:
free((void*)node->symbol.name);//free the memory allocated by strdup
free((void*)node);//here I free the node itself
我已经设法解决了所有泄漏问题,除了一个:
8 bytes in 1 blocks are definetely lost in loss record 1 of 1
at 0x4C2DB6B: malloc (vg_replace_malloc.c:299)
by 0x4ECE489: strdup (in /usr/lib64/libc-2.25.so)
by 0x400EE7: symbol_add (symbol.c:117)
我检查了 symbol.c 的第 117 行,果然它就是我在上面粘贴的使用 strdup 的地方。我不确定如何清除与此相关的内存,以免出现任何内存泄漏。请帮忙!非常感谢。
最佳答案
因为代码片段似乎是正确的,基本假设应该是您strdup
到一个已经分配的指针
要解决这个问题,我会添加:
/* free memory if it is already allocated */
if ( newSymbol->symbol.name )
free( newSymbol->symbol.name);
newSymbol->symbol.name = strdup(name); //name is a (const) char* that is a parameter to function I'm in.
newSymbol->symbol.addr = addr;
虽然重要的是要提到即使它解决了问题,我还是建议继续调试您的代码,因为看起来您实际上并没有正确释放内存
希望对你有帮助...
关于c - 即使在我释放它之后,Valgrind 也发现了字符串的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755654/