Chris Lutz
Chris Lutz

Reputation: 75399

Looking before leaping

Ignoring multithreading issues, is the following guaranteed to work:

int can_alloc(size_t i)
{
    void *p = malloc(i);
    if(p == NULL) return 0;
    free(p);
    return 1;
}

// later
if(can_alloc(10))
{
    char *c = malloc(10); // no need to verify, we already did?
    memcpy(c, "something", 10);
}

This is mostly out of curiosity. I have no plans to use this for anything, but I believe it should be guaranteed to work, and it would be informative to know for sure.

Upvotes: 2

Views: 69

Answers (2)

John Sloper
John Sloper

Reputation: 1821

Answer above is correct. On many linux versions it is even worse as it uses optimistic memory allocation. So that even if malloc() returns non-null it does not mean the memory is really available. More info here.

Upvotes: 1

sje397
sje397

Reputation: 41822

No. Even without multi-threading, the malloc call is obtaining (memory) resources from the OS. Usually (Windows, Linux, Mac, etc) the OS can do things that affect the available resources while your program is executing - at any time. That means between your check and your actual allocation, the memory might become 'unavailable'.

If you have unusually complete control of the OS, then it might be possible to make this robust - but it would be extremely tricky.

Upvotes: 5

Related Questions