Use free
and malloc
. This will NOT lead to fragmentation problems.
Modern allocators are quite resistant to memory fragmentation. Today, a rather pathological program is required to solve the problems of fragmentation. Fragmentation was a more serious problem when our programs directly accessed physical RAM, but with virtual memory a large βholeβ in the program heap did not need to consume any resources.
In addition, due to the size of the buffers, most allocators will request a dedicated area from the kernel for each buffer. On Linux / OS X / BSD, this means anonymous mmap
behind the scenes for each buffer. This can lead to fragmentation of the address space, but the virtual address space is mostly free for a 64-bit system, and several hundred megabytes is also not a problem in the 32-bit version.
So use free
and malloc
.
Alternative:. You may be lucky enough to make each buffer larger than you need. The malloc
method works on modern Unix, on any pages that you donβt write, so as not to consume memory.
So, if you malloc
buffer 500 MB, but use only the first 100 MB, your program does not actually use more memory than if you malloc
100 MB buffer and used all this. Thus, you get more fragmentation of the address space, but this is not a problem in 64-bit systems, and you can always adjust the distribution size to work on 32-bit systems.
Regarding suggestions for using mmap
, just think of malloc
/ free
as a simpler interface to mmap
/ munmap
, which is for large distributions (1 MiB is a common threshold).
source share