我可以将Valgrind memcheck的输出"可能丢失"视为"绝对丢失"吗?
可能丢失或"可疑":找到指向块内部的指针.指针可能最初指向开头并且已经移动,或者它可能完全不相关.Memcheck认为这样的块是"可疑的",因为不清楚它的指针是否仍然存在.
绝对丢失或"泄露":最糟糕的结果是没有找到指向该块的指针.该块被归类为"泄露",因为程序员不可能在程序退出时释放它,因为没有指向它的指针.这可能是在程序的某些早期点丢失指针的症状
les*_*ana 61
是的,我建议治疗可能丢失的严重因为肯定丢失.换句话说,修复代码直到完全没有丢失.
当您使用持有它的相同指针遍历数组时,可能会发生丢失.您知道可以通过减去索引来重置指针.但是的valgrind不能判断它是否是一个编程错误,或者你是聪明的故意这样做.这就是它警告你的原因.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
char* s = "string";
// this will allocate a new array
char* p = strdup(s);
// move the pointer into the array
// we know we can reset the pointer by subtracting
// but for valgrind the array is now lost
p += 1;
// crash the program
abort();
// reset the pointer to the beginning of the array
p -= 1;
// properly free the memory for the array
free(p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编
$ gcc -ggdb foo.c -o foo
Run Code Online (Sandbox Code Playgroud)
Valgrind的报告
$ valgrind ./foo
...
==31539== Process terminating with default action of signal 6 (SIGABRT): dumping core
==31539== at 0x48BBD7F: raise (in /usr/lib/libc-2.28.so)
==31539== by 0x48A6671: abort (in /usr/lib/libc-2.28.so)
==31539== by 0x10917C: main (foo.c:14)
==31539==
==31539== HEAP SUMMARY:
==31539== in use at exit: 7 bytes in 1 blocks
==31539== total heap usage: 1 allocs, 0 frees, 7 bytes allocated
==31539==
==31539== LEAK SUMMARY:
==31539== definitely lost: 0 bytes in 0 blocks
==31539== indirectly lost: 0 bytes in 0 blocks
==31539== possibly lost: 7 bytes in 1 blocks
==31539== still reachable: 0 bytes in 0 blocks
==31539== suppressed: 0 bytes in 0 blocks
...
Run Code Online (Sandbox Code Playgroud)
如果你删除abort()
那么Valgrind将报告根本没有丢失内存.如果没有中止,指针将返回到数组的开头,内存将free
正确显示.
这是一个微不足道的例子.在足够复杂的代码中,指针可以并且将返回到存储器块的开头不再明显.代码其他部分的更改可能会导致可能丢失的内容明显丢失.这就是为什么你应该关心可能丢失的原因.