How to get the largest available chunk of memory that can be allocated?

1.3k views Asked by At

How can I get the largest size (continious) in bytes my application can allocate in one malloc call without returning out of memory? (biggest available chunk)

P.S.: I would like a general answer for both if I want to allocate it and if I don't want to allocate it (so this question does not need to be reasked).

2

There are 2 answers

11
Eugeniu Rosca On

The following piece of code will provide an approximate answer, especially for real-time deterministic memory allocators found in realtime operating systems. It is not targeted for a general purpose OS:

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

#define INCR 100000

int main(void){
    unsigned long i;
    for(i=1;;i=i+INCR) {
        void *ret = malloc(i);
        if (ret) {
            free(ret);
        }
        else {
            printf("malloc could not allocate memory of size: %ld bytes!\n", i);
            return 0;
        }
    }
}
2
too honest for this site On

I presume you are asking about a (somewhat) modern desktop or server OS.

The problem is: any answer can be invalid already when the result is returned. Reasons are other processes, threads, memory fragmentation, etc. As others stated in comments already, an OS might even report more memory than available - inlcuding swap. The idea is that the allocated memory might only be sparsely used by a process, so only actually accesses memory pages will be provided as required, malloc() itself will not reserve any memory in advance.

It is also often not a good idea to allocate as much memory as possible, as that can result in exessive swapping or starving/thrashing other processes. So, just allocate the memory you actually need.

**Conclusion: ** Just forget about it! Allocate the memory you require, not more, not less. If you need dynamic memory, think about dynamic structures like lists and trees or use realloc() (but use it well thought).

Sidenote:

Do not feel tempted to try allocated blocks in increasing size until you get NULL returned. This can easily result in fragmentation, and you might not be able to allocate even the previous largest block size (for similar reasons as stated above).


For embedded OSes, there might be a completely different answer.