fir*_*iku 9 c memory-management stdio
我正在编写一个库,并希望使它绝对与资源无关,这也意味着库应该使用用户提供的内存分配功能.库允许用户也设置自己的错误处理函数,这些函数以错误消息作为参数调用,如下所示:
typedef void (*error_handler)(const char* msg);
Run Code Online (Sandbox Code Playgroud)
库代码自己准备错误消息,就像那样(消息格式化失败的情况):
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "Oops found at file '%s' line %d", __FILE__, __LINE__);
Run Code Online (Sandbox Code Playgroud)
但是我可以确定snprintf不会为malloc的内部使用分配更多内存,显然会绕过用户提供的分配例程吗?我的Linux系统中的手册页对此保持沉默.
像任何库程序,sprintf并snprintf 可能会或可能不会在内部使用分配内存.
它们不会为结果字符串分配内存.必须由调用者以某种方式分配该内存,并将其地址作为第一个参数传递.如果分配的内存不够大,那么sprintf将有未定义的行为(因为没有办法告诉它有多少空间可用),snprintf并将截断结果(假设size参数是准确的).
如果实现sprintf或snprintf分配内存并且没有安排它被释放,那将是内存泄漏.这样的泄漏实际上不会违反语言标准(对资源分配几乎没有什么说法),但它将被视为该实现中的一个错误.
特别是,如果您自己的代码使用自己的内存分配器而不是malloc,您调用的任何库函数都可以在malloc内部调用,除非您使用某些特定于系统的功能来调用malloc(即使在标准库中)调用您的分配器.fopen()例如,特别有可能为缓冲区分配内存.
如果你做一些事情来替代标准库的调用malloc与调用你自己的分配器,你需要确保你也更换任何来电realloc,calloc和free,以及可能的一个或多个特定的系统程序.例如,程序完成时运行的清理代码将关闭打开的文件,这可能涉及调用free.
根据glibc,newlibc源代码,它们都malloc在某些情况下使用,但不是在最有可能的情况下使用.
如果你想malloc知道当前代码执行的时间或任何其他函数,你可以在Linux上挂钩这样的libc函数:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void *malloc(size_t size) {
static void *(*original_malloc)(size_t) = NULL;
if (! original_malloc) {
/* get the pointer to the original malloc */
original_malloc = dlsym(RTLD_NEXT, "malloc");
}
void *rv = original_malloc(size);
printf("allocated %zd bytes of memory\n", size);
return rv;
}
Run Code Online (Sandbox Code Playgroud)
将其编译为共享对象
gcc -Wl,--no-as-needed -shared -ldl -fPIC hook.c -o hook.so
Run Code Online (Sandbox Code Playgroud)
并给出了代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
char buf[256];
char *malloced;
printf("about to run sprintf\n");
sprintf(buf, "%.250f", 0.123456789);
printf("done\n");
printf("about to run asprintf\n");
asprintf(&malloced, "foo");
free(malloced);
printf("done\n");
}
Run Code Online (Sandbox Code Playgroud)
编译成prog,你可以运行它:
% LD_PRELOAD=./hook.so ./prog
about to run sprintf
done
about to run asprintf
allocated 100 bytes of memory
allocated 4 bytes of memory
done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7042 次 |
| 最近记录: |