在全球范围内覆盖的malloc在Visual C ++

问题描述:

我试图找出一种方法来覆盖全局malloc和在Visual C相关职能++(2005年)。我的设置是静态链接的运行时库DLL中同时包含我自己的C ++ code,外部C ++和C code的。我想做到的是让DLL的用户设置的内存分配函数自己的实现。

I'm trying to figure out a way to globally override malloc and related functions in visual c++ (2005). My setup is a dll with statically linked runtime library that consists of both my own c++ code, external c++ and c code. What I want to accomplish is to allow a user of the dll to set their own implementations of the memory allocation functions.

解决方案我无法使用:


  • 重写新的和全球的删除,
    有很多外部的C函数库
    我的code碱基,这意味着这将不
    捕捉许多分配。

  • #defining的malloc到一个不同的符号。这将迫使我按这个定义为使用的所有外部库的构建设置,我真的想避免这种情况。

我不关心的事情有关。


  • 如果任何外部库在一些其他的方式来分配内存(HeapAlloc,内存映射文件或任何他们拿出了),我接受,这将无法正常通过重写的malloc跟踪。

最合理的解决方案,我可以拿出以某种方式与链接过程的干扰,并确保我自己的malloc被链接而不是标准的人,preferably我希望能够使用旧的malloc功能为默认值。

The most reasonable solution I can come up with is somehow interfering with the link process and making sure my own malloc is being linked instead of the standard ones, preferably I'd like to be able to use the old malloc functions as default.

在谷歌法律约束工具的好像他们补丁的code在运行时手动功能,让钩子函数调用原函数之前被调用。这真的是这样做的最佳方式?

In google perf-tools it seems like they patch the code of the functions manually at runtime to allow a hook function to be called before calling the original function. Is this really the best way of doing this?

下面是在Linux上真实的,但可以适用于永盛VISUAL C ++为好。

The following is true on Linux, but may be applicable to Win's visual C++ as well.


  1. malloc的功能可按由系统的glibc库提供。可执行文件是默认反对它联系在一起的。

  1. Malloc funciton is provided by system library glibc. The executable is by default linked against it.

当程序运行时,动态加载注意到可执行需求malloc函数并寻找提供它的第一个库。

When the program is run, the dynamic loader notices that executable needs malloc function and looks for the first library that provides it.

由于glibc的是(默认),最后在该列表中发现该库可能不是glibc的。

As glibc is (by default) the last in that list, the library found may not be glibc.

除非你静态链接的glibc到可执行文件,明显的解决方案是将可执行针对提供你自己的malloc链接库,并确保它不会覆盖系统的之一。

Unless you have statically linked glibc into the executable, the obvious solution is to link the executable against the library that provides your own malloc, and make sure that it does override the system's one.