简体   繁体   中英

C++ empty program memory leak

Consider the following code

int main(){
    return 0;
}

I compiled it with g++ and passed the output to valgrind. The output is the following.

==11752== HEAP SUMMARY:
==11752==     in use at exit: 72,704 bytes in 1 blocks
==11752==   total heap usage: 1 allocs, 0 frees, 72,704 bytes allocated
==11752== 
==11965== LEAK SUMMARY:
==11965==    definitely lost: 0 bytes in 0 blocks
==11965==    indirectly lost: 0 bytes in 0 blocks
==11965==      possibly lost: 0 bytes in 0 blocks
==11965==    still reachable: 72,704 bytes in 1 blocks
==11965==         suppressed: 0 bytes in 0 blocks

However, compiling the same code in C with gcc produces this valgrind output:

==11771== HEAP SUMMARY:
==11771==     in use at exit: 0 bytes in 0 blocks
==11771==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==11771== 
==11771== All heap blocks were freed -- no leaks are possible

It looks like compiling

It looks like the empty C++ program actually allocates memory and does not free it (it's not a disaster since it's a "still reachable" leak), and I have no clue why this is happening.

I did this test on linux (solus os) with g++ 6.3.

Can someone explain what's going on ?

it's not a disaster since it's a "still reachable" leak

It's not even a leak . It is extremely common for programs to not free a block of memory that some global points to; doing the free ing is

  • unnecessary work that just makes the program exit slower
  • may cause complications if multiple threads are running (exiting thread may yank carpet from under the other thread)
  • may cause complications if other parts of cleanup can access this block, etc. etc.

I have no clue why this is happening.

To get a clue, run valgrind --leak-check=full --show-reachable=yes ... . That will tell you where the block was allocated.

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