在 C 中为 malloc 和 free 创建一个包装函数 [英] Create a wrapper function for malloc and free in C

查看:15
本文介绍了在 C 中为 malloc 和 free 创建一个包装函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 C 中为 freemalloc 创建包装函数,以帮助通知我内存泄漏.有谁知道如何声明这些函数,所以当我调用 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?

推荐答案

您有几个选择:

  1. 特定于 GLIBC 的解决方案(主要是 Linux).如果您的编译环境是 glibcgcc,则首选方法是使用 malloc 钩子.它不仅可以让您指定自定义的 mallocfree,还可以通过堆栈上的返回地址来识别调用者.

  1. GLIBC-specific solution (mostly Linux). If your compilation environment is glibc with gcc, the preferred way is to use malloc hooks. Not only it lets you specify custom malloc and free, but will also identify the caller by the return address on the stack.

特定于 POSIX 的解决方案.mallocfree 定义为可执行文件中原始分配例程的包装器,这将覆盖"来自 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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆