Why do I get "Killed" when I run this program?
#include <stddef.h>
int main() {
constexpr size_t N{5'000'000'000};
unsigned int *bigdata;
bigdata = new unsigned int[N];
for (size_t i=0; i<N; i++)
bigdata[i] = i;
return 0;
}
Setting N
to a much larger value, such as 50'000'000'000, results in an std::bad_alloc
. With a smaller value, such as 1'000'000'000, the program works fine. But with 5'000'000'000, it fails quite unpredictably while writing to the array, abruptly printing "Killed" on the console and exiting with code 137. Is there any way to know what size of arrays it is safe to use on a given system?
Additional info
Someone marked this question as redundant, linking to How to get available memory C++/g++?. It is not unthinkable that this question has been answered before, but the linked page is not it. Using the code example provided in the top-rated answer still generates the same error. Here is the full program:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
unsigned long long getTotalSystemMemory() {
long pages = sysconf(_SC_PHYS_PAGES);
long page_size = sysconf(_SC_PAGE_SIZE);
return pages * page_size;
}
int main() {
size_t N = getTotalSystemMemory();
printf("Size: %zu \n", N);
unsigned int *bigdata = (unsigned int *)malloc(N);
for (size_t i = 0; i < N / sizeof(unsigned int) - 1; i++)
bigdata[i] = i;
return 0;
}
The output:
Size: 16'439'369'728 // Separators added manually
Killed