Question

Or do you just have to do it and check errno and/or the pointer to see if you succeeded?

Was it helpful?

Solution

Are you asking if you can find out before you call malloc how many bytes are available for you to use?

If so, the answer is no. Even if you could, the answer may not be very valuable to you. The reason why is you can never know how much memory is available, you can only know how much memory was available. This is a very important distinction because it has an affect on the way you can properly utilize an API.

For instance, lets assume there was such a function called available_memory. This code looks correct but is horribly broken

size_t size = GetSizeToAllocate();
if ( size < available_memory() ) {
  // No need to check the answer because there is enough memory
  SomeType* p = malloc(size);
}

The reason why is that some other thread could come in between the if statement and the malloc statement and do it's own allocation. That could reduce the overal memory in the system and hence change available_memory's return.

Even worse is the available amount of memory in the system does not determine how much memory can be allocated with malloc. What's important for malloc (and any other memory alloc operation) is how much contiguous memory is available.

OTHER TIPS

Trying won't necessarily help because some OSes (like Linux) use an optimistic memory allocation strategy - even if you get a non-NULL result from malloc() it doesn't mean you have the requested chuck of memory at your service.

More here

Seems there is no way to do it.

There is no way to do that in C. Any solution would be OS-specific, and I don't know if it would be useful enough to implement.

If you know at the start of a program how much memory you will need and the program must not fail while running it's common to just alloc all the memory you need at the start as one big block and then manage it yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top