nbr*_*bro 4 c memory pointers memory-management
我一直在为我创建的一个简单程序创建测试。我总是使用类似这样的方法检查使用 malloc 分配内存是否失败
int* ptr = malloc(sizeof(int) * x);
if(!ptr){
//...
exit(1); // but it could also not terminate abnormally and do something else
}
Run Code Online (Sandbox Code Playgroud)
但通常,至少对于我的程序,malloc永远不会失败,而那些我无法真正确定性地测试malloc失败时的情况。
我的问题是:如果我无法控制 malloc 是否会失败,我该如何测试程序是否会出现内存分配失败?当 malloc 失败时,我应该怎么做才能进行确定性测试?
假的malloc:
#define malloc(...) NULL
int* ptr = malloc(sizeof(int) * x);
Run Code Online (Sandbox Code Playgroud)
当我需要在不同阶段测试内存分配失败时,我使用了xmalloc()这样的函数:
static int fail_after = 0;
static int num_allocs = 0;
static void *xmalloc(size_t size)
{
if (fail_after > 0 && num_allocs++ >= fail_after)
{
fputs("Out of memory\n", stderr);
return 0;
}
return malloc(size);
}
Run Code Online (Sandbox Code Playgroud)
测试工具(同一源文件的一部分)可以设置fail_after为任何合适的值,并num_allocs在每次新测试运行之前重置为零。
int main(void)
{
int no1 = 5;
for (fail_after = 0; fail_after < 33; fail_after++)
{
printf("Fail after: %d\n", fail_after);
num_allocs = 0;
test_allocation(no1);
}
printf("PID %d - waiting for some data to exit:", (int)getpid());
fflush(0);
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以安排调用xmalloc()代替 'real' malloc():
#define malloc(x) xmalloc(x)
Run Code Online (Sandbox Code Playgroud)
这将放在定义之后xmalloc()——尽管如果需要的话,有办法解决这个问题。您可以通过各种方式调整事物:也限制总大小,安排每第N次分配失败,安排在 M 次成功分配后连续分配N次失败,等等。