我需要编写单一测试来包装abort()系统调用。包装中止()系统调用时的奇怪行为
这里是一个代码段:
gcc -Wl,--wrap=abort,--wrap=free,--wrap=malloc -ggdb -o test test.c
运行它给出以下输出:
$ ./test
pre malloc: p=(nil)
allocated 40 bytes @0xd06010
post malloc p=0xd06010
pre abort
post abort
pre free
freeing @0xd06010
post free
所以
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
extern void __real_abort(void);
extern void * __real_malloc(int c);
extern void __real_free(void *);
void __wrap_abort(void)
{
printf("=== Abort called !=== \n");
}
void * __wrap_malloc(int s)
{
void *p = __real_malloc(s);
printf("allocated %d bytes @%p\n",s, (void *)p);
return p;
}
void __wrap_free(void *p)
{
printf("freeing @%p\n",(void *)p);
return __real_free((void *)p);
}
int main(int ac, char **av)
{
char *p = NULL;
printf("pre malloc: p=%p\n",p);
p = malloc(40);
printf("post malloc p=%p\n",p);
printf("pre abort\n");
//abort();
printf("post abort\n");
printf("pre free\n");
free(p);
printf("post free\n");
return -1;
}
然后我使用下面的命令行编译此一切安好。 现在让我们来测试相同的代码,但与中止()调用未注释:
$ ./test
pre malloc: p=(nil)
allocated 40 bytes @0x1bf2010
post malloc p=0x1bf2010
pre abort
=== Abort called !===
Segmentation fault (core dumped)
我真的不明白,为什么我得到一个分段错误而中止嘲讽()系统调用... 每一个建议是欢迎!
我在x86_64内核上运行Debian GNU/Linux 8.5。机器是基于Core i7的笔记本电脑。
打印错误后你不需要真的中止吗?因为错误是不可恢复的。 –
以双下划线开头的名称保留给标准库和用于任何用途的实现。它们不应该用于用户代码中。 – Olaf
@ Jean-FrançoisFabre事实上,我们的目标是避免在单一的测试环境中调用真正的abort()。 (以便我的测试框架可以检索测试状态并打印出报告)。 – binarym