2

这个是在运行一个使用地址清理程序构建的程序时出现的,这让我很好奇。

gperftools 源代码包含以下函数:

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;
  }
}

定义InitModule如下

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

我们的地址清理器(当然不是 valgrind)抱怨MallocExtension对象的内存泄漏。显然,这是对的。但是为什么首先要进行分配呢?

我拒绝认为开发自己的内存分配器的人会犯如此微不足道的错误。还有一个针对 valgrind 的明确检查。那么分配的目的是什么?

4

1 回答 1

1

是的,在各种谷歌代码(即不仅仅是 gperftools)中,故意泄漏在启动时分配的单例对象是很常见的。思想既不是初始化也不是破坏顺序是明确定义的。因此,试图在进程关闭时释放这些单例是要求各种超级难以跟踪的问题。

更多信息:https ://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables

于 2018-02-03T22:09:03.690 回答