C/C++的printf会调用malloc()

排查内存问题(或相关的疑难杂症)时,可能一句printf就能让bug出现,或者赶走bug。你可能觉得很神奇,但这并不神奇。

至少我们可以在 Linux-x64 下,通过 malloc hook,来验证当前的编译环境下, printf 确实是调用了 malloc。 而 malloc 底层也不是吃素的, 默认是 glibc 的 ptmalloc 这个内存管理器, 如果本身你的程序把内存控制块写坏了, 继续 malloc 那就容易出现问题, 也就表现为 printf 影响了 bug 的出现。

来看代码。 伸手党可以直接看 godbolt:

https://godbolt.org/z/PPYMW613d

hook.c

c 复制代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <malloc.h> // malloc_usable_size
#include <inttypes.h>
#include <pthread.h>

// 颜色定义
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define RESET "\x1b[0m"

// 线程局部存储防止递归
static __thread int reentrancy_guard = 0;

// 真实函数指针
static void* (*real_malloc)(size_t size) = NULL;
static void (*real_free)(void* ptr) = NULL;
static void* (*real_realloc)(void* ptr, size_t size) = NULL;

// 初始化函数,使用 pthread_once 确保只初始化一次
static pthread_once_t init_once = PTHREAD_ONCE_INIT;

static void init_real_functions() {
    //real_malloc = dlsym(RTLD_NEXT, "malloc");
    real_malloc = (void* (*)(size_t))dlsym(RTLD_NEXT, "malloc");
    real_free = (void (*)(void*))dlsym(RTLD_NEXT, "free");
    real_realloc = (void* (*)(void*, size_t))dlsym(RTLD_NEXT, "realloc");
    if (!real_malloc || !real_free || !real_realloc) {
        const char *error = "Error in `dlsym`\n";
        write(STDERR_FILENO, error, sizeof("Error in `dlsym`\n") - 1);
        _exit(1);
    }
}

// malloc 钩子实现
void* malloc(size_t size) {
    if (reentrancy_guard) {
        return real_malloc ? real_malloc(size) : NULL;
    }

    pthread_once(&init_once, init_real_functions);

    reentrancy_guard++;
    void* ptr = real_malloc(size);
    reentrancy_guard--;

    if (ptr) {
        char buffer[256];
        int len = snprintf(buffer, sizeof(buffer), BLUE "malloc %ld %p\n" RESET, size, ptr);
        write(STDERR_FILENO, buffer, len);
    }

    return ptr;
}

// free 钩子实现
void free(void* ptr) {
    if (reentrancy_guard) {
        if (real_free) real_free(ptr);
        return;
    }

    pthread_once(&init_once, init_real_functions);

    reentrancy_guard++;
    if (ptr) {
        size_t size = malloc_usable_size(ptr);
        char buffer[256];
        int len = snprintf(buffer, sizeof(buffer), GREEN "free %ld %p\n" RESET, size, ptr);
        write(STDERR_FILENO, buffer, len);
    }
    real_free(ptr);
    reentrancy_guard--;
}

// realloc 钩子实现
void* realloc(void* ptr, size_t size) {
    if (reentrancy_guard) {
        return real_realloc ? real_realloc(ptr, size) : NULL;
    }

    pthread_once(&init_once, init_real_functions);

    reentrancy_guard++;
    void* new_ptr = real_realloc(ptr, size);
    reentrancy_guard--;

    if (new_ptr) {
        char buffer[256];
        int len = snprintf(buffer, sizeof(buffer), YELLOW "realloc %ld %p %p\n" RESET, size, ptr, new_ptr);
        write(STDERR_FILENO, buffer, len);
    }

    return new_ptr;
}

编译:

bash 复制代码
gcc -shared -fPIC hook4.c -o hook.so -ldl -O2

使用

cpp 复制代码
int main()
{
    printf("Hello, World");
    return 0;
}
bash 复制代码
g++ main.cpp
LD_PRELOAD=./hook.so ./a.out

输出内容:

bash 复制代码
malloc 4096 0x3a842b0
Hello, World
相关推荐
夏玉林的学习之路37 分钟前
正则表达式
数据库·c++·qt·mysql·正则表达式
夜晚中的人海1 小时前
【C++】模拟算法习题
c++·算法·哈希算法
报错小能手1 小时前
C++笔记(面向对象)多态(编译时 运行时)
c++·笔记
晨非辰1 小时前
《数据结构风云》递归算法:二叉树遍历的精髓实现
c语言·数据结构·c++·人工智能·算法·leetcode·面试
太理摆烂哥1 小时前
map&&set的使用
c++·stl
Dream it possible!1 小时前
LeetCode 面试经典 150_链表_LRU 缓存(66_146_C++_中等)(哈希表 + 双向链表)
c++·leetcode·链表·面试
mailangduoduo1 小时前
命令行传参及调试——vscode平台
c++·人工智能·vscode·代码调试·命令行传参
敲上瘾1 小时前
Linux系统C++开发工具(四)—— jsoncpp 使用指南
linux·服务器·网络·c++·json
ceclar1232 小时前
C++日期与时间
开发语言·c++
Minecraft红客2 小时前
复原大唐3d项目测试版
c++·3d·青少年编程·电脑·娱乐