gpt4 book ai didi

Valgrind:可能丢失可以被视为绝对丢失吗?

转载 作者:行者123 更新时间:2023-12-03 08:36:52 24 4
gpt4 key购买 nike

我可以将 Valgrind memcheck 的输出“可能丢失”视为“肯定丢失”吗?

Possibly lost, or “dubious”: A pointer to the interior of the block is found. The pointer might originally have pointed to the start andhave been moved along, or it might be entirely unrelated. Memcheckdeems such a block as “dubious”, because it's unclear whether or not apointer to it still exists.

Definitely lost, or “leaked”: The worst outcome is that no pointer to the block can be found. The block is classified as “leaked”,because the programmer could not possibly have freed it at programexit, since no pointer to it exists. This is likely a symptom ofhaving lost the pointer at some earlier point in the program

最佳答案

是的,我建议将可能丢失与肯定丢失一样严重。换句话说,修复你的代码,直到完全没有损失。
当您使用持有它的相同指针遍历数组时,可能会丢失。你知道你可以通过减去索引来重置指针。但是 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;
}
编译
$ gcc -ggdb foo.c -o foo
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

...
如果您删除 abort()那么 Valgrind 将报告没有任何内存丢失。不中止,指针将返回数组的开头,内存为 free d 正确。
这是一个简单的例子。在足够复杂的代码中,指针可以并且将返回到内存块的开头不再是显而易见的。代码其他部分的更改可能会导致可能丢失成为绝对丢失。这就是为什么你应该关心可能丢失的原因。

关于Valgrind:可能丢失可以被视为绝对丢失吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3537713/

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