This article delves into the issue of why simply including the
The provided code snippet is a simple "hello world" program that includes the
#include <iostream> int main() { return 0; }
Running this program through Valgrind with leak checking and tracking origins enabled reveals the following output:
==27671== Memcheck, a memory error detector ... (output truncated) ... ==27671== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1 ==27671== at 0x4C2AB9D: malloc (vg_replace_malloc.c:296) ==27671== by 0x4EC060F: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) ... (output truncated)
This indicates that 72,704 bytes are still reachable despite not explicitly allocating any memory in the program.
While Valgrind's warning may be concerning, it's important to understand that this is a common behavior for C programs. Many implementations of the C standard library employ their own memory pool allocators, which pool memory for destructed objects and reuse them later. This optimized memory management technique reduces memory overhead and improves performance.
However, since Valgrind operates under the assumption that all allocated memory should be returned to the operating system upon program termination, it reports the memory held by these pools as still reachable. This is not necessarily a bug in the program or Valgrind, but rather a difference in expectation.
If you wish to eliminate the still reachable warnings with Valgrind, you can disable the STL (Standard Template Library) memory pools by modifying the compiler settings. Here are a few methods:
With GCC versions 2.91 to 3.1, you can compile the program using -D__USE_MALLOC to force the STL to use malloc and free memory promptly. However, this option has been removed in GCC 3.3 and later.
For GCC versions 3.2.2 and later, you can set the environment variable GLIBCPP_FORCE_NEW before running the program. For GCC 3.4 and above, the environment variable name is GLIBCXX_FORCE_NEW.
With newer compilers, you can use the -fno-optimize-sibling-calls flag to disable sibling call optimization, which includes the STL memory pool optimization.
Including the
The above is the detailed content of Why Does Including `` in C Cause Valgrind\'s \'Still Reachable\' Warnings?. For more information, please follow other related articles on the PHP Chinese website!