创建malloc和free在C包装函数 [英] Create a wrapper function for malloc and free in C
问题描述
我试图创建包装功能免费的malloc在C帮我通知内存泄漏。有谁知道,当我调用malloc()和free(如何让这些声明函数),它会调用我的自定义功能,而不是标准的lib功能?
Hey, I am trying to create wrapper functions for free and malloc in C to help notify me of memory leaks. Does anyone know how to declare these functions so when I call malloc() and free() it will call my custom functions and not the standards lib functions?
推荐答案
您有几种选择:
-
GLIBC-具体的解决方案(主要是Linux)的。如果您的编译环境是
的glibc
与GCC
中,preferred的方法是使用的malloc挂钩。它不仅可以让你自定义的指定的malloc
和免费
,而是返回地址栈上也将识别呼叫者
GLIBC-specific solution (mostly Linux). If your compilation environment is
glibc
withgcc
, the preferred way is to use malloc hooks. Not only it lets you specify custommalloc
andfree
, but will also identify the caller by the return address on the stack.
特定POSIX的解决方案。定义的malloc
和免费
作为包装在你的可执行文件原来的分配程序,这将在libc的覆盖的版本。包装里面,你可以调用到原来的的malloc
的实施,可以查找使用的 则dlsym
与 RTLD_NEXT
处理。您的应用程序或库定义的包装功能需求与 -ldl
链接。
POSIX-specific solution. Define malloc
and free
as wrappers to the original allocation routines in your executable, which will "override" the version from libc. Inside the wrapper you can call into the original malloc
implementation, which you can look up using dlsym
with RTLD_NEXT
handle. Your application or library that defines wrapper functions needs to link with -ldl
.
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
void* malloc(size_t sz)
{
void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc");
printf("malloc\n");
return libc_malloc(sz);
}
void free(void *p)
{
void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free");
printf("free\n");
libc_free(p);
}
int main()
{
free(malloc(10));
return 0;
}
Linux特有的。您可以在 LD_ preLOAD
环境指定它们覆盖从动态库非侵入性功能变量。
Linux specific. You can override functions from dynamic libraries non-invasively by specifying them in the LD_PRELOAD
environment variable.
LD_PRELOAD=mymalloc.so ./exe
的Mac OSX具体。
同Linux的,除了你将使用 DYLD_INSERT_LIBRARIES
环境变量。
Same as Linux, except you will be using DYLD_INSERT_LIBRARIES
environment variable.
这篇关于创建malloc和free在C包装函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!