内存泄漏:Definitely lost 和 possibly lost

Memory leakage :Definitely lost and possibly lost

当我 运行 valgrind 通过在我的代码中添加泄漏时,我得到泄漏,因为第一次分配块仍然可以到达,然后显示为 9 blocks.Possibly 丢失正在显示由于代码的其他部分。为什么会这样?

main()
{
........

char *ptr;
For(i=0;i<10;i++)
{
ptr=malloc(sizeof * ptr);
}

.....

}

举报:

HEAP SUMMARY:
==13832==     in use at exit: 202,328 bytes in 62 blocks
==13832==   total heap usage: 332 allocs, 270 frees, 283,928 bytes allocated
==13832==
==13832== LEAK SUMMARY:
==13832==    definitely lost: 90 bytes in 9 blocks
==13832==    indirectly lost: 0 bytes in 0 blocks
==13832==      possibly lost: 202,180 bytes in 49 blocks
==13832==    still reachable: 58 bytes in 4 blocks
==13832==         suppressed: 0 bytes in 0 blocks
==13832== Rerun with --leak-check=full to see details of leaked memory

memcheck manual 是这样说的:

  • "Possibly lost". […] This means that a chain of one or more pointers to the block has been found, but at least one of the pointers is an interior-pointer. This could just be a random value in memory that happens to point into a block, and so you shouldn't consider this ok unless you know you have interior-pointers.

因此,只有在堆上有嵌套数据结构时才会发生这种情况,其中指针指向分配的偏移量,而不是直接指向开头。

除了 Florian 的回答之外,这里还有一些内部指针的示例

  1. 内存管理器。例如,您知道您将分配很多相同大小的小内存块,因此您编写了一个内存管理器来分配大块并将它们细分为您的小块。这些子块分配是内部指针。
  2. 内存调试器。在这种情况下,您分配的内存比请求的多,额外的内存用于填充分配的内存。返回给客户端的指针是内部指针。
  3. Pascal 字符串等数据结构。在这里,您为字符串及其大小分配内存。大小在字符串之前,因此指向字符串开头的指针是内部指针。