Home >Backend Development >C++ >Why Does Valgrind Report Still Reachable Memory with a Trivial Program Using ``?

Why Does Valgrind Report Still Reachable Memory with a Trivial Program Using ``?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 01:47:10331browse

Why Does Valgrind Report Still Reachable Memory with a Trivial Program Using ``?

Valgrind: Memory still reachable with trivial program using

This question is about a Valgrind warning about still reachable memory in a trivial program that includes the header.

Problem:

A trivial program that includes the header produces a Valgrind warning about still reachable memory. This is unexpected because no objects from the standard library were allocated in the program itself.

#include <iostream>

int main() {
  return 0;
}

Answer:

The Valgrind warning is not a bug, but a feature. Many implementations of the C standard library use their own memory pool allocators. Memory for destructed objects is not immediately freed and given back to the OS, but kept in the pool for later reuse. The memory pools are also not freed when the program exits, causing Valgrind to report the memory as still reachable.

Solution:

There are several ways to disable pool caching and force the STL to use malloc and free memory as soon as possible:

  • With GCC 2.91 to 3.1:
g++ -D__USE_MALLOC ...
  • With GCC 3.2.2 and later:
export GLIBCPP_FORCE_NEW=1
  • With GCC 3.4 and later:
export GLIBCXX_FORCE_NEW=1

Additional Notes:

  • This solution may slow down the program.
  • This behavior is not a bug in the library, but rather a feature to improve performance.
  • Other headers, such as and , do not have this issue because they do not use memory pool allocators.

The above is the detailed content of Why Does Valgrind Report Still Reachable Memory with a Trivial Program Using ``?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn