Theo Walton
Theo Walton

Reputation: 1105

How to create a function that uses up all malloced memory

I want to make a function that I can stick before the stuff in a test main and it will use up all the space for malloc (causing future allocations to fail). The problem is that once the function finishes everything seems to get freed...

#include <stdlib.h>

void    breakmalloc(void)
{
    int *i;
    int n;

    n = 1;
    i = &n;
    while (n)
    {
        while (i)
        {
            i = malloc(n);
            if (i)
                n = n + n;
        }
        n = n / 2;
        i = &n;
    }
}

it exits the function when I test it so it would seem that all of the space has been used up but as soon as the function finishes I can then malloc other stuff in future functions.

Upvotes: 2

Views: 77

Answers (3)

Terry.Lee
Terry.Lee

Reputation: 69

#include <stdlib.h>
#include <stdio.h>

void breakmalloc(void) 
{
    char *buff = NULL;
    int size = 1024;
    while (1) {
        buff = (char *)malloc(size);
        if (buff) {
            memset(buff, 1, size); //must use it, or optimized by system
        } else {
            printf("memory insufficient!");
            break;
        }
    }
}

try like this

Upvotes: 0

dbush
dbush

Reputation: 223917

Some operating systems such an Linux perform optimistic memory allocation. That means that whatever memory is returned by malloc and family is not immediately allocated and therefore not necessarily available. So even if you were to allocate 100GB of memory malloc would still probably return non-NULL.

The memory won't actually get allocated until you use it. So to force it, you should memset the block.

i = malloc(n);
if (i) {
    memset(i, 0, n);
    n = n + n;
}

Upvotes: 2

mattn
mattn

Reputation: 7723

I don't know if the test result using your trick handled green/red correctly since memory is exhausted. If your code call malloc to allocate memory, and you want test it. I guess you've better to use simple trick.

#ifdef TEST
#  undef malloc
#  define malloc(x) (NULL)
#endif

Upvotes: 3

Related Questions