Hard
malloc() beyond available memory under default overcommit
System is Linux with default overcommit settings (vm.overcommit_memory=0) and only ~200MB of RAM+swap actually free. Predict what happens when this runs.
main.cpp
#include <cstdlib>
#include <cstring>
#include <cstdio>
int main() {
const size_t GB = 1024UL * 1024 * 1024;
char* p = (char*)malloc(GB); // 1GB, but only ~200MB is actually free
if (!p) {
printf("malloc failed\n");
return 1;
}
printf("malloc succeeded, address = %p\n", (void*)p);
memset(p, 0xAB, GB); // touch every page
printf("memset complete\n");
return 0;
}29 of 53 in Operating Systems