Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make malloc fail voluntarily in order to test the cases when malloc fails

I've been creating tests for a simple program that I created. I always check if the allocation of memory using malloc fails using something like this

int* ptr = malloc(sizeof(int) * x);

if(!ptr){
    //...
    exit(1); // but it could also not terminate abnormally and do something else
}

But usually, for my programs at least, malloc never fails, and those I can't really deterministically test the cases when malloc fails.

My question is: how can I test a program for the case of a memory allocation failure, if I've not control on the fact if malloc will fail or not? What should I do to test deterministically when malloc fails?

like image 515
nbro Avatar asked Dec 18 '22 15:12

nbro


1 Answers

When I needed to test memory allocation failures at different stages, I used a function xmalloc() like this:

static int fail_after = 0;
static int num_allocs = 0;

static void *xmalloc(size_t size)
{
    if (fail_after > 0 && num_allocs++ >= fail_after)
    {
        fputs("Out of memory\n", stderr);
        return 0;
    }
    return malloc(size);
}

The test harness (part of the same source file) could set fail_after to any suitable value, and reset num_allocs to zero before each new test run.

int main(void)
{
    int no1 = 5;

    for (fail_after = 0; fail_after < 33; fail_after++)
    {
        printf("Fail after: %d\n", fail_after);
        num_allocs = 0;
        test_allocation(no1);
    }

    printf("PID %d - waiting for some data to exit:", (int)getpid());
    fflush(0);
    getchar();

    return 0;
}

Then you can arrange to call xmalloc() in lieu of the 'real' malloc():

#define malloc(x)    xmalloc(x)

That would be placed after the definition of xmalloc() — though there are ways to work around that if need so be. You can tweak things all sorts of ways: limit the total size too, arrange to fail every Nth allocation, arrange to fail for N successive allocations after M successful ones, etc.

like image 126
Jonathan Leffler Avatar answered Jan 26 '23 00:01

Jonathan Leffler