Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

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 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...