Why am I getting "Invalid distribution size: 4294967295 bytes" instead of std :: bad_alloc exception?

I wrote the following code snippet to allocate memory for an array:

try {
    int n = 0;
    cin >> n;
    double *temp = new double[n];
    ...
}
catch(exception& e) {
    cout << "Standard exception: " << e.what() << endl;
    exit(1);
}

Of course, I check n for negative values, etc., but when I enter some large number for 536 * (10 ^ 6), I don't get a bad-alloc exception, but "Invalid distribution size: 4294967295 bytes" Crash .

eg. I enter n = 536 * (10 ^ 6) → bad-alloc exception I enter n = 537 * (10 ^ 6) → Invalid distribution: 4294967295 Bytes → Failed

Any ideas why this is happening?

+4
source share
3 answers

new double[n] operator new n * sizeof(double). operator new , , .

: n sizeof(double) , operator new , , , size_t. , , , , .

, , n <= SIZE_MAX / sizeof(double), .

+12

Visual Studio , " " .

Properties → Linker → System → Enable Large Addresses, " (/LARGEADDRESSAWARE)"

+4

In a 32-bit system, the address space of virtual memory cannot exceed 2 ^ 31-1 (4294967295) bytes.

You are trying to allocate 536000000*sizeof(double)bytes, which is obviously more.

0
source

Source: https://habr.com/ru/post/1539259/


All Articles