如何在 C 语言中测试 malloc 故障?

How to test malloc failure in C?

提问人:Karl ZHU 提问时间:12/7/2022 更新时间:12/8/2022 访问量:350

问:

我写了一些代码,我需要处理失败或.我知道如果内存分配失败,它会返回,我写了如下内容:Cmalloc()realloc()NULL

    char *str = (char *)malloc(sizeof(char));
    if (str == NULL)
    {
        puts("Malloc Failed.");
        // do something
    }
    // do something else

那么问题来了,我该如何测试这部分代码呢?

手动用完机器上的内存是不可能的。因此,我想限制它可以使用的最大内存大小。

我可以指定我的程序在编译/运行时可以使用的最大内存大小吗?或者有什么技术可以做到这一点吗?

供您参考,我用标准编写代码,用 编译并在 Linux 环境中运行它。Cgcc

提前非常感谢。

C GCC 内存 malloc

评论

0赞 Gerhardh 12/7/2022
在你的测试中,你可以用你自己的函数替换 .或者你可以添加一些来假装失败mallocNULL#ifdef MEMORY_TEST str=NULL;#endif
0赞 chux - Reinstate Monica 12/7/2022
@Karl ZHU 替换为你自己的函数,时而调用,时而返回。malloc()malloc()NULL
0赞 hyde 12/7/2022
分配足够大的块,大小应该很好,因为它给你无符号的长长,每个比特都设置为 1,即。最大值。~0ull
1赞 hyde 12/7/2022
此外,在 Linux 和 MacOs 等上,.man ulimit

答:

2赞 dbush 12/7/2022 #1

您可以创建一个测试文件,该文件实质上覆盖 .malloc

首先,使用宏重新定义为存根函数,例如 。然后包含要测试的源文件。这会导致调用被替换为可以返回您想要的任何内容的调用。然后,您可以调用该函数进行测试。mallocmy_mallocmallocmy_malloc

#include <stdio.h>
#include <stdlib.h>

#define malloc(x) my_malloc(x)

#include "file_to_test.c"

#undef malloc

int m_null;

void *my_malloc(size_t n)
{
    return m_null ? NULL : malloc(n);
}

int main()
{
    // test null case
    m_null = 1;
    function_to_test();
    // test non-null case
    m_null = 0;
    function_to_test();
    return 0;
}

评论

0赞 chux - Reinstate Monica 12/7/2022
不错,但只允许 1 个紫外线。嗯,OTOH ....
2赞 Mittous Issmail 12/8/2022 #2

您可以简单地给 malloc 一个大数字来分配,它将无法分配您尝试分配的大小。