简体   繁体   中英

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

you can simply give malloc a big number to allocate and it will fail to allocate the size you trying to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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