简体   繁体   English

如何在C中测试malloc失败?

[英]How to test malloc failure in C?

I wrote some code in C and I need to handle the situation that fail to malloc() or realloc() .我在C中写了一些代码,我需要处理malloc()realloc()失败的情况。 I know that if memory allocation failed, it will return NULL , and I wrote something as follow:我知道如果 memory 分配失败,它会返回NULL ,我写了如下内容:

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

So the problem is, how can I test this part of code?那么问题来了,我该如何测试这部分代码呢?

It is impossible to run out of my memory on my machine by hand.我的memory在我的机器上手动跑完是不可能的。 So I want to restrict the biggest memory size it can use.所以我想限制它可以使用的最大 memory 大小。

Can I specify the maximum memory size my program can use when I compile/run it?我可以指定我的程序在编译/运行时可以使用的最大 memory 大小吗? Or is there any technique to do it?或者有什么技术可以做到吗?

For your information, I write code in standard C , compile it with gcc , and run it on Linux environment.供您参考,我在标准C中编写代码,使用gcc编译,并在 Linux 环境中运行。

Many thanks in advance.提前谢谢了。

You can create a test file that essentially overrides malloc .您可以创建一个实质上覆盖malloc的测试文件。

First, use a macro to redefine malloc to a stub function, for example my_malloc .首先,使用宏将malloc重新定义为存根 function,例如my_malloc Then include the source file you want to test.然后包含要测试的源文件。 This causes calls to malloc to be replaced with my_malloc which can return whatever you want.这会导致对malloc的调用被my_malloc替换,后者可以返回任何你想要的。 Then you can call the function to test.然后可以拨打function进行测试。

#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;
}

you can simply give malloc a big number to allocate and it will fail to allocate the size you trying to.您可以简单地给 malloc 一个大的数字来分配,它将无法分配您尝试分配的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM