提问人:Karl ZHU 提问时间:12/7/2022 更新时间:12/8/2022 访问量:350
如何在 C 语言中测试 malloc 故障?
How to test malloc failure in C?
问:
我写了一些代码,我需要处理失败或.我知道如果内存分配失败,它会返回,我写了如下内容:C
malloc()
realloc()
NULL
char *str = (char *)malloc(sizeof(char));
if (str == NULL)
{
puts("Malloc Failed.");
// do something
}
// do something else
那么问题来了,我该如何测试这部分代码呢?
手动用完机器上的内存是不可能的。因此,我想限制它可以使用的最大内存大小。
我可以指定我的程序在编译/运行时可以使用的最大内存大小吗?或者有什么技术可以做到这一点吗?
供您参考,我用标准编写代码,用 编译并在 Linux 环境中运行它。C
gcc
提前非常感谢。
答:
2赞
dbush
12/7/2022
#1
您可以创建一个测试文件,该文件实质上覆盖 .malloc
首先,使用宏重新定义为存根函数,例如 。然后包含要测试的源文件。这会导致调用被替换为可以返回您想要的任何内容的调用。然后,您可以调用该函数进行测试。malloc
my_malloc
malloc
my_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 一个大数字来分配,它将无法分配您尝试分配的大小。
评论
malloc
NULL
#ifdef MEMORY_TEST str=NULL;#endif
malloc()
malloc()
NULL
~0ull
man ulimit