Search code examples
c++memorymallocmmaperrno

mmap() Allocation Fails With Large Numbers?


On macOS Big-Sur With 32GB of Ram of which 24+ are free I ran the following program:

void *void_new_block = mmap(nullptr, sizeof(MyClass) + 300000, PROT_READ | PROT_WRITE, MAP_ANONYMOUS, -1,
                            0);
if (void_new_block == (void *) (-1)) {
    std::cout << strerror(errno) << std::endl;
    return nullptr;
}

But mmap keeps failing and I see on screen the following message:

Invalid argument

What's the reason for such strange behaviour?

Plus, sizeof(MyClass) = 48


Solution

  • According to the documentation:

    Conforming applications must specify either MAP_PRIVATE or MAP_SHARED.

    Linux has a similar restriction:

    This behavior is determined by including exactly one of the following values in flags

    MAP_SHARED

    MAP_SHARED_VALIDATE

    MAP_PRIVATE