Home > Blockchain >  How to test malloc failure in C?
How to test malloc failure in C?

Time:12-08

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related