You should not take my word for it. For the moment I can't have access to a FreeBSD installation (I am stuck on a Linux install), so the code was not tested properly. That's why most of my sentences begin with "I think that". But I think you can execute this code on any FreeBSD install and you will understand how it works just by looking at the output of the program. I could have made that program prettier, but it would not have been a good introduction to mmap()
.
I don't think you can make it "prettier" the way I meant it. Although
mmap()
is specified in POSIX, anonymous mappings aren't specified there, so it's also unclear whether this "re-mapping" page-wise would
really work.
But if this code works on FreeBSD, it would at least mean you can write a program on FreeBSD reserving a large contiguous address space without having to rely on overcommit, which is already kind of cool.
In addition, if you want to write portable code, malloc()
is a good bet. Otherwise you have to abstract the memory handling in some kind of library, and use mmap()
for Unix systems and VirtualAlloc()
for Windows systems (and potentially other low-level memory functions for other operating systems). And VirtualAlloc()
cannot do everything mmap()
can.
That's one reason I think some extended (and portable) interface would be nice *). Of course, supporting Windows in addition to
mmap()
as a backend would be more work for an implementation...
Probably it's much too late for all my thoughts here because overcommit is just an "accepted fact" and people wouldn't start adopting better interfaces in different OS
and applications ?. So you can just add the "OOM killer" to the list of unforseeable environmental events that can always bring down your application/service in an unexpected way...
-----
*)
edit: For simple usecases like a potentially growing array, a simple extension like this could be enough:
Code:
void *mreserve(size_t size);
void *mallocfrom(void *pool, size_t size);
void munreserve(void *pool);
Of course, this won't suffice if what you need is some sparse data structure...