I just learned about heaps and stack memory allocations and was curious how much i can allocate on heap. as i see heap allocation gives pointer to memory where requested amount of contiguous bytes are free. so i wrote following code to do a binary search for the the maximum amount i can allocate.
#include <iostream>
#include <chrono>
#include <cassert>
using namespace std;
int main ( void ) {
size_t lo = 0, hi = -1ll; hi >>= 1; // i am doing this to avoid overflow.
while (lo + 1 != hi) {
char * ptr = NULL;
ptr = (char*) malloc((lo+hi)>>1);
if (ptr != NULL) lo = (lo+hi)>>1;
else hi = (lo+hi)>>1;
free(ptr);
}
cout << lo << " is amount of bytes of memory that we could allocate on this system's heap.\n";
cout << (lo>>10) << " KB\n";
cout << (lo>>20) << " MB\n";
cout << (lo>>30) << " GB\n";
// additional code.
// this part is to read and write at n uniformly distant cells in 20GB of memory.
auto start = chrono::high_resolution_clock::now();
int * arr = (int *) malloc(5ll<<32); // 20GB
bool ok = true;
const int n = 10; // n means 5 * 2 ^ n cells to write and read.
for (long long i=0; i<(5<<n); ++i) {
assert((5ll<<30) > (i<<(30-n)));
arr[i << (30-n)] = 23;
ok &= arr[i << (30-n)] == 23;
}
auto end = chrono::high_resolution_clock::now();
long long elapsed = chrono::duration_cast<chrono::milliseconds>(end - start).count();
cout << "Elapsed time : " << elapsed << "ms\n";
cout << (ok ? "ok is True\n" : "ok is False\n");
free(arr);
return 0;
}
Output
27672117247 is amount of bytes of memory that we could allocate on this system's heap.
27023551 KB
26390 MB
25 GB
Elapsed time : 13ms
ok is True
i know output can change with time on same machine. but i didn't expected it to be around ~22GB always, when my system's RAM has capacity of only 8GB. what is going on here ?