简体   繁体   中英

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:

==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. 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. 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.

Using --show-reachable=yes can tell you more. 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.


PS double array[size]; is ill-formed, since size is not a compile time constant expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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