从包装器宏中调用 Malloc
Calling Malloc from Within a Wrapper Macro
我正在尝试编写一些宏来调试我正在处理的一些代码,但我遇到了 运行 问题,而且我不确定如何解决它。我想用另一个函数包装 malloc,然后使用宏来替换包装器的任何调用。问题是包装器本身必须调用 malloc。我有一个这样的头文件:
memory.h:
#define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__ )
#define free(X) my_free( X )
void *my_malloc(size_t size, const char *file, int line, const char*func);
void my_free(void *ptr);
然后我有一个关联的 .c 文件来定义包装函数。
memory.c:
#include "memory.h"
void *my_malloc(size_t size, const char *file, int line, const char*func) {
void *ptr = malloc(size);
/* do stuff */
return ptr;
}
void my_free(void *ptr) {
/* do stuff */
free(ptr);
}
最后,我有了希望宏起作用的代码。
main.c
int main(int argc, char **argv) {
int *my_ptr = malloc( sizeof(int) );
free(my_ptr);
return 0;
}
我 运行 遇到的问题是该函数变为递归并导致程序崩溃。我的问题是,有没有一种方法可以让我的实现与头文件分开,并且仍然可以从中访问真正的 malloc 函数(即 .c 文件知道调用正确的 malloc 而不是预处理器替换它)?
提前致谢!
一种方法是 #undef
malloc
和 free
宏 memory.c
:
memory.c:
#undef malloc
#undef free
void *my_malloc(size_t size, const char *file, int line, const char*func)
{
...
}
...
void my_free(void *ptr)
{
...
}
另一种方法是将 my_malloc
和 my_free
函数声明为 extern
。这样,包含 malloc
和 free
的 memory.h
不应包含在 memory.c
.
中
memory.c:
/* #include "memory.h" */
extern void *my_malloc(size_t size, const char *file, int line, const char*func)
{
...
}
...
extern void my_free(void *ptr)
{
...
}
memory.h
extern void *my_malloc(size_t size, const char *file, int line, const char*func);
...
extern void my_free(void *ptr);
我正在尝试编写一些宏来调试我正在处理的一些代码,但我遇到了 运行 问题,而且我不确定如何解决它。我想用另一个函数包装 malloc,然后使用宏来替换包装器的任何调用。问题是包装器本身必须调用 malloc。我有一个这样的头文件:
memory.h:
#define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__ )
#define free(X) my_free( X )
void *my_malloc(size_t size, const char *file, int line, const char*func);
void my_free(void *ptr);
然后我有一个关联的 .c 文件来定义包装函数。
memory.c:
#include "memory.h"
void *my_malloc(size_t size, const char *file, int line, const char*func) {
void *ptr = malloc(size);
/* do stuff */
return ptr;
}
void my_free(void *ptr) {
/* do stuff */
free(ptr);
}
最后,我有了希望宏起作用的代码。
main.c
int main(int argc, char **argv) {
int *my_ptr = malloc( sizeof(int) );
free(my_ptr);
return 0;
}
我 运行 遇到的问题是该函数变为递归并导致程序崩溃。我的问题是,有没有一种方法可以让我的实现与头文件分开,并且仍然可以从中访问真正的 malloc 函数(即 .c 文件知道调用正确的 malloc 而不是预处理器替换它)?
提前致谢!
一种方法是 #undef
malloc
和 free
宏 memory.c
:
memory.c:
#undef malloc
#undef free
void *my_malloc(size_t size, const char *file, int line, const char*func)
{
...
}
...
void my_free(void *ptr)
{
...
}
另一种方法是将 my_malloc
和 my_free
函数声明为 extern
。这样,包含 malloc
和 free
的 memory.h
不应包含在 memory.c
.
memory.c:
/* #include "memory.h" */
extern void *my_malloc(size_t size, const char *file, int line, const char*func)
{
...
}
...
extern void my_free(void *ptr)
{
...
}
memory.h
extern void *my_malloc(size_t size, const char *file, int line, const char*func);
...
extern void my_free(void *ptr);