在 C 中为 malloc 和 free 创建一个包装函数 [英] Create a wrapper function for malloc and free in C
问题描述
我正在尝试在 C 中为 free
和 malloc
创建包装函数,以帮助通知我内存泄漏.有谁知道如何声明这些函数,所以当我调用 malloc()
和 free()
时,它会调用我的自定义函数而不是标准库函数?
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
,则首选方法是使用 malloc 钩子.它不仅可以让您指定自定义的malloc
和free
,还可以通过堆栈上的返回地址来识别调用者.
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
和 free
定义为可执行文件中原始分配例程的包装器,这将覆盖"来自 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
");
return libc_malloc(sz);
}
void free(void *p)
{
void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free");
printf("free
");
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.
这篇关于在 C 中为 malloc 和 free 创建一个包装函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!