简体   繁体   English

为什么调用堆栈数组会导致内存泄漏?

[英]Why is a call-stack array causing a memory leak?

I have a small code snippet that asks the user for 5 doubles, when running valgrind --leak-check=full ./exercise1 , I get a memory leak, saying: 我有一个小代码段,要求用户在运行valgrind --leak-check=full ./exercise1时进行5次加倍操作,出现内存泄漏,说:

==6765==
==6765== HEAP SUMMARY:
==6765==     in use at exit: 72,704 bytes in 1 blocks
==6765==   total heap usage: 8 allocs, 7 frees, 75,037 bytes allocated
==6765==
==6765== LEAK SUMMARY:
==6765==    definitely lost: 0 bytes in 0 blocks
==6765==    indirectly lost: 0 bytes in 0 blocks
==6765==      possibly lost: 0 bytes in 0 blocks
==6765==    still reachable: 72,704 bytes in 1 blocks
==6765==         suppressed: 0 bytes in 0 blocks
==6765== Reachable blocks (those to which a pointer was found) are not shown.
==6765== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==6765==
==6765== For counts of detected and suppressed errors, rerun with: -v
==6765== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I'm not sure why my this code is leaving memory. 我不确定为什么我的这段代码会留下内存。 There is no heap allocated array being used nor any pointers being used anywhere in the code. 在代码中的任何地方都没有使用堆分配的数组,也没有使用任何指针。 This means that I won't need to use any delete[] to delete any objects. 这意味着我将不需要使用任何delete []来删除任何对象。 I'm confused why I'm just getting left over memory still. 我很困惑为什么我还剩下内存。 Here is my code: 这是我的代码:

#include <iostream>
using namespace std;

int main(){

}

It is typical for a C++ implementation to allocate memory for internal usage. 对于C ++实现,通常为内部使用分配内存。 It is also common pattern to not free dynamic memory that is used for global state of the program. 不释放用于程序全局状态的动态内存也是一种常见的模式。 The "reachable" memory reported by valgrind is in no way related to your code, as your code does not allocate any dynamic memory. valgrind报告的“可访问”内存与您的代码无关,因为您的代码未分配任何动态内存。

Using --show-reachable=yes can tell you more. 使用--show-reachable=yes可以告诉您更多信息。 I'll show output for the program 我将显示程序的输出

int main(){}

==10673== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==10673==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10673==    by 0x4E78745: pool (eh_alloc.cc:123)
==10673==    by 0x4E78745: __static_initialization_and_destruction_0 (eh_alloc.cc:262)
==10673==    by 0x4E78745: _GLOBAL__sub_I_eh_alloc.cc (eh_alloc.cc:338)
==10673==    by 0x40106B9: call_init.part.0 (dl-init.c:72)
==10673==    by 0x40107CA: call_init (dl-init.c:30)
==10673==    by 0x40107CA: _dl_init (dl-init.c:120)
==10673==    by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)

ld is the dynamic linker / loader library on Linux. ld是Linux上的动态链接程序/加载程序库。


PS double array[size]; PS double array[size]; is ill-formed, since size is not a compile time constant expression. 由于size不是编译时常数表达式,因此格式不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM