简体   繁体   English

C++ 空程序内存泄漏

[英]C++ empty program memory leak

Consider the following code考虑以下代码

int main(){
    return 0;
}

I compiled it with g++ and passed the output to valgrind.我用 g++ 编译它并将输出传递给 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:但是,使用 gcc 在 C 中编译相同的代码会产生这个 valgrind 输出:

==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.看起来空的 C++ 程序实际上分配了内存并且没有释放它(这不是灾难,因为它是一个“仍然可以访问”的泄漏),我不知道为什么会发生这种情况。

I did this test on linux (solus os) with g++ 6.3.我用 g++ 6.3 在 linux (solus os) 上做了这个测试。

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 isfree ing 是

  • 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 ... .要获得线索,请运行valgrind --leak-check=full --show-reachable=yes ... That will tell you where the block was allocated.这将告诉您块的分配位置。

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

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