Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for when malloc returns NULL

I'm trying to replicate the strdup function in C. It's part of an exercise for school. I'd like to unit test it, including the case where malloc returns NULL and sets errno to ENOMEM.

I'm on OSX 10.8.

I've tried limiting the stacksize, then datasize, realizing malloc allocates on the heap:

limit stacksize 0
limit datasize 0

Confirmation that limiting should have worked:

my-host% limit
cputime         unlimited
filesize        unlimited
datasize        0kB
stacksize       0kB
coredumpsize    0kB
addressspace    unlimited
memorylocked    unlimited
maxproc         709
descriptors     256

However, even with a limit of 0kB for the stack size, I am able to run programs just fine. So I'm thinking there might be a restriction on my host on the minimum stack size.

How else could I test the case where malloc returns NULL?

like image 257
conradkleinespel Avatar asked Oct 03 '22 09:10

conradkleinespel


1 Answers

I suggest you fake the memory allocation failure. For example, I needed to test memory failure during allocation of a 3D array (lots of memory to clean up), so I used a framework where the function xmalloc() was called to get memory, and the test program controlled when xmalloc() would fail.

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", stdout);
        return 0;
    }
    return malloc(size);
}

...code using xmalloc...

int main(int argc, char **argv)
{
    int no1 = 5;
    int fail_limit = 33;

    if (argc == 2)
        fail_limit = atoi(argv[1]);

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

    return 0;
}

Write your strdup() surrogate to use xmalloc() instead of malloc(). Test it more or less as shown. You can get fancier with the 'out of memory' requirements; this is rudimentary but effective.

like image 59
Jonathan Leffler Avatar answered Oct 20 '22 02:10

Jonathan Leffler