Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使malloc自动失败,以便在malloc失败时测试用例_C_Pointers_Memory_Memory Management - Fatal编程技术网

使malloc自动失败,以便在malloc失败时测试用例

使malloc自动失败,以便在malloc失败时测试用例,c,pointers,memory,memory-management,C,Pointers,Memory,Memory Management,我一直在为我创建的一个简单程序创建测试。我总是使用类似这样的方法检查使用malloc分配内存是否失败 int* ptr = malloc(sizeof(int) * x); if(!ptr){ //... exit(1); // but it could also not terminate abnormally and do something else } 但通常,至少对我的程序来说,malloc永远不会失败,而且当malloc失败时,我无法真正确定地测试用例 我的问题是

我一直在为我创建的一个简单程序创建测试。我总是使用类似这样的方法检查使用malloc分配内存是否失败

int* ptr = malloc(sizeof(int) * x);

if(!ptr){
    //...
    exit(1); // but it could also not terminate abnormally and do something else
}
但通常,至少对我的程序来说,
malloc
永远不会失败,而且当
malloc
失败时,我无法真正确定地测试用例


我的问题是:如果我无法控制malloc是否会失败,那么如何在内存分配失败的情况下测试程序?当malloc失败时,我应该如何进行决定性测试

假a
malloc

#define malloc(...) NULL
int* ptr = malloc(sizeof(int) * x);
#define malloc(x)    xmalloc(x)

当我需要在不同阶段测试内存分配失败时,我使用了一个函数
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);
}
malloc(-1);
测试线束(同一源文件的一部分)可以将
fail\u after
设置为任何合适的值,并在每次新测试运行之前将
num\u 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;
}

这将放在
xmalloc()
的定义之后,尽管有一些方法可以解决这一问题,如果需要的话。您可以通过各种方式进行调整:也限制总大小,安排每N次分配失败,安排在M次成功分配后N次连续分配失败,等等。

您可能希望使用负值调用malloc,如下所示:

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);
}
malloc(-1);
这将使
malloc
返回
NULL
,并相应地将
errno
设置为
12
(“无法分配内存”)


老实说,这不是一个“真正的”内存不足场景,但我认为出于测试目的,这可以做到。

这似乎是一个更好的解决方案,与道格拉斯的建议相比。。。也许我甚至可以在编译时传递(比如)一个指令的值或类似的东西,这样我就不必手动将它添加到每个
.c
,只要我想测试
malloc
的这个失败?如果可能的话(因为我不是预处理器指令方面的专家),或者
#定义malloc my_alloc
使用
calloc()
或者
rand()实现
my_alloc
在奇数时间失败。您可以创建自己的
malloc
函数,并将其注入
LD\u PRELOAD
。nbro,您的操作系统是什么?是linux+glibc吗?Glibc的malloc具有重新定义malloc的指针。您可以将malloc重新定义为您自己的版本,该版本将根据某个随机变量或某个内部状态失败(每1000次调用失败一次),并且在大多数情况下,它将只调用标准malloc。或者,您可以在内存大小上定义一些
ulimit
s并使用标准malloc。详细信息:使用
xmalloc()
返回0size==0
时,code>不是失败返回。