开发者

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(). I know that if memory allocation failed, it will return NULL, and I wrote something as follow:

    char *str = (char *)malloc(sizeof(char));
    if (str == NULL)
    {
        puts("Malloc Failed.");
        // do something
    }
    // do som开发者_高级运维ething 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. So I want to restrict the biggest memory size it can use.

Can I specify the maximum memory size my program can use when I compile/run it? 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.

Many thanks in advance.


You can create a test file that essentially overrides malloc.

First, use a macro to redefine malloc to a stub function, for example 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. Then you can call the function to test.

#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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜