You should understand that if you have 10 GB of free RAM, it does not mean that you can allocate an array of 10 GB. Imagine that the letter e
denotes an empty gigabyte and the letter b
denotes a busy one. And in real life, your RAM will look something like this
eebeebbeeebeebe
We can notice that here 10 GB are free, but we cannot allocate an array on 10 GB (let's not forget, at arrays elements go consistently in storage). So the only way I can advise is to go through the dimensions until you find the largest free.
So your code might looks like this(but NOTE, you can improve size by using std::realloc
instead of new
+ delete
, and I'm using binary search to imrove perfomance)
size_t min = 0;
size_t max = std::numeric_limits<size_t>::max();
int *ptr = new int[min];
while (max - min > 1)
{
size_t middle = (max - min) / 2 + min;
try
{
int *temp = new int[middle];
min = middle;
delete[] ptr;
ptr = temp;
}
catch (const std::exception &e)
{
max = middle;
continue;
}
}
std::cout << "max_size is " << min << '\n';