Search code examples
c++memory-leaksmallocgperftools

Apparent memory leak in gperftools


This one comes up when running a program that was built with the address sanitizer and made me curious.

The gperftools source code contains the following function:

void MallocExtension::Register(MallocExtension* implementation) {
  InitModule();
  // When running under valgrind, our custom malloc is replaced with
  // valgrind's one and malloc extensions will not work.  (Note:
  // callers should be responsible for checking that they are the
  // malloc that is really being run, before calling Register.  This
  // is just here as an extra sanity check.)
  if (!RunningOnValgrind()) {
    current_instance = implementation;
  }
}

With InitModule defined as follows

static void InitModule() {
  if (current_instance != NULL) {
    return;
  }
  current_instance = new MallocExtension; // pointless?
#ifndef NO_HEAP_CHECK
  HeapLeakChecker::IgnoreObject(current_instance);
#endif
}

Our address sanitizer (not valgrind, of course) complains about a memory leak for the MallocExtension object. Apparently, it is right. But why is this allocation in there in the first place?

I refuse to think that people developing their own memory allocator would make such a trivial mistake. There is also an explicit check against valgrind. So what is the purpose of the allocation?


Solution

  • Yes, it is common in various google codes (i.e. not just gperftools) to deliberately leak singleton objects malloced at startup. The thinking is neither initialization nor destruction order is well-defined. So trying to free such singletons at process shutdown is asking for various super-difficult to track problems.

    More here: https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables