每当调用malloc/free时输出到stderr [英] Outputting to stderr whenever malloc/free is called

查看:74
本文介绍了每当调用malloc/free时输出到stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux/GCC/C ++中,每当调用malloc/free/new/delete时,我都要记录一些东西到stderr.我试图了解库的内存分配,因此我想在运行单元测试时生成此输出.我使用valgrind进行mem泄漏检测,但是我找不到用于使它仅用于日志分配的选项.

With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allocations.

有什么想法吗?我正在寻找最简单的解决方案.重新编译该库不是一种选择.

Any ideas? I'm looking for the simplest possible solution. Recompiling the library is not an option.

推荐答案

malloc_hook(3) 允许您全局插入自己的malloc函数. (还有__realloc_hook __free_hook等.为简单起见,我将它们省略了.)

malloc_hook(3) allows you to globally interpose your own malloc function. (There's __realloc_hook __free_hook etc. as well, I've just left them out for simplicity.)

#include <stdio.h>
#include <malloc.h>

static void *(*old_malloc_hook)(size_t, const void *);

static void *new_malloc_hook(size_t size, const void *caller) {
    void *mem;

    __malloc_hook = old_malloc_hook;
    mem = malloc(size);
    fprintf(stderr, "%p: malloc(%zu) = %p\n", caller, size, mem);
    __malloc_hook = new_malloc_hook;

    return mem;
}

static void init_my_hooks(void) {
    old_malloc_hook = __malloc_hook;
    __malloc_hook = new_malloc_hook;
}

void (*__malloc_initialize_hook)(void) = init_my_hooks;


$ cat >mem.c <<'EOF'
(the code above)
EOF
$ cc -fPIC -shared -o mem.so mem.c
$ LD_PRELOAD=./mem.so ls
0x7ffc14931adc: malloc(5) = 0xb40010
0x7ffc1492c6b0: malloc(120) = 0xb40030
0x7ffc1497f61a: malloc(12) = 0xb40010
0x7ffc1492be38: malloc(776) = 0xb400b0
…

printf可能会调用malloc,这就是我们暂时撤消该挂接的原因.如果您以任何方式钩住malloc,请注意这一点.

printf might call malloc, which is why we undo the hook temporarily. Be careful of this if when you hook malloc in any way.

这篇关于每当调用malloc/free时输出到stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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