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.
No. Even without multi-threading, the
malloccall 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.