为什么valgrind无法检测到由于重新分配而导致的这种内存泄漏?

问题描述 投票:0回答:1

我不明白为什么valgrind(版本3.14)没有在此程序中检测到可能的内存泄漏:

#include <stdlib.h>

int main() {
  int *p = malloc(sizeof(int));
  p = realloc(p, 2 * sizeof(int));

  free(p);

  return 0;
}

[C99标准(ISO / IEC 9899:1999,第314页)表示关于realloc

如果无法分配用于新对象的内存,则不会释放旧对象,并且其值不变。 [...]realloc函数返回一个指向新对象的指针(该对象可能具有相同的值作为指向旧对象的指针),如果新对象不能为null,则返回null指针分配。

因此p可能是NULL,但先前分配有malloc的存储单元仍然存在,这是否可能导致内存泄漏?

如果我使用gcc -std=c99编译程序,并使用--tool=memcheck --leak-check=full --track-origins=yes执行valgrind,则会显示以下消息:

==313618== Memcheck, a memory error detector
==313618== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==313618== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==313618== Command: ./a.out
==313618== 
==313618== 
==313618== HEAP SUMMARY:
==313618==     in use at exit: 0 bytes in 0 blocks
==313618==   total heap usage: 2 allocs, 2 frees, 12 bytes allocated
==313618== 
==313618== All heap blocks were freed -- no leaks are possible
==313618== 
==313618== For counts of detected and suppressed errors, rerun with: -v
==313618== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
c memory-leaks valgrind dynamic-memory-allocation realloc
1个回答
1
投票

Valgrind不会分析您的代码;它分析您的代码执行的操作。

在此特定运行中realloc没有失败,因此没有内存泄漏,因此valgrind没有什么可报告的:

所有堆块已释放

这就是valgrind所知道的。

© www.soinside.com 2019 - 2024. All rights reserved.