Malloc () on Linux - “no guarantee that memory is really available”?

I am making a game in which the world is divided into pieces of data describing the world. I store chunks in a dynamically allocated array, so I have to use malloc()when initializing world data structures.

Reading the malloc()man page , there is a note:

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc()non-NULL returns, there is no guarantee that memory is actually available. In the event that it turns out that the system has lost memory, one or more processes will be killed by the OOM Killer. For more information, see Description / proc / sys / vm / overcommit _memory and / proc / sys / vm / oom _adj in proc(5), and the Linux kernel source file Documentation / VM / overcommit accounting.

If Linux is configured to use optimized memory allocation, does this mean that it does not always return all the memory that I requested in a call malloc()?

I read that optimistic memory allocation is disabled, changing the kernel, but I do not want to do this.

So, is there a way to check if the program assigned the requested amount?

+4
source share
2 answers

This is not what you need to deal with in terms of the application. Users who don’t want random processes killed by the “OOM killer” to disconnect themselves through

echo "2" > /proc/sys/vm/overcommit_memory

It is their choice, not yours.

. "" , malloc . , ( MAP_POPULATE ), //. , , , .

, , malloc . .

+6

malloc mmap, MAP_POPULATE, .

#include <sys/mman.h>

// allocate length bytes and prefault the memory so 
// that it surely is mapped
void *block = mmap(NULL, length, PROT_READ|PROT_WRITE, 
       MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE,
       -1, 0);

// free the block allocated previously
// note, you need to know the size
munmap(block, length);

, , mmap :

int fd = open('world.bin', 'r+');
void *block = mmap(NULL, <filesize>, PROT_READ|PROT_WRITE,
    MAP_SHARED, fd, 0);

world.bin , block; - , , linux , .


, , :

, _BSD_SOURCE _SVID_SOURCE. ( _GNU_SOURCE , , Linux.) : MAP_32BIT, MAP_ANONYMOUS ( MAP_ANON), MAP_DENYWRITE, MAP_EXECUTABLE, MAP_FILE, MAP_GROWSDOWN, MAP_HUGETLB, MAP_LOCKED, MAP_NONBLOCK, MAP_NORESERVE, MAP_POPULATE MAP_STACK.

+1

All Articles