'Changing M_MMAP_THRESHOLD and allocating memory above and below it
I recently learned that when we call malloc and ask for more memory than the M_MMAP_THRESHOLD, the system will allocate a memory segment using mmapinstead of using malloc and allocating on the heap. The following code was written to check that.
#include <iostream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <malloc.h>
using namespace std;
int main() {
const auto M = 4; // M = 4, 32, 64
const auto threshold = M * 1024;
if (mallopt(M_MMAP_THRESHOLD, threshold) != 1) {
throw invalid_argument{"mallopt failed: "s + strerror(errno)};
}
auto below = malloc(threshold - 8);
auto above = malloc(threshold + 8);
cout << "&below: " << below << "\n";
cout << "&above: " << above << "\n";
return 0;
}
The results that I get when using these three different values for M are:
M=4 Both memory blocks allocated on the heap. (unexpected)
&below: 0x558b85810eb0
&above: 0x558b85811eb0
M=16 One block on the heap, one mapping in VM space. (expected)
&below: 0x557b31501eb0
&above: 0x7f0b0d66d010
M=32 Two mappings on VM space. (unexpected)
&below: 0x7f1fee27d010
&above: 0x7f1fedd1c010
My question is why don't we see the expected result in all cases but only at the second?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
