Why am I getting “Invalid Allocation Size: 4294967295 Bytes” instead of an std::bad_alloc exception?

房东的猫 提交于 2019-12-01 04:18:58

问题


I wrote the following piece of code 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'm checking n for negative values etc. but when I enter some large Number over 536*(10^6) I'm not getting a bad-alloc exception but a "Invalid Allocation Size: 4294967295 Bytes" Crash.

E.G. I enter n = 536*(10^6) --> bad-alloc exception I enter n = 537*(10^6) --> Invalid Allocation Size: 4294967295 Bytes --> Crash

Any ideas why this is happening?


回答1:


Calling new double[n] calls the global operator new function with a size of n * sizeof(double). If operator new then finds it cannot fulfil the request, it throws an exception.

However, that cannot happen here: the product of n and sizeof(double) is so large that it is actually not possible to call operator new at all, because the size you requested just plain doesn't fit in a size_t. Implementations vary in how they handle this, but yours evidently aborts the program.

If you want to handle this, you can check that n <= SIZE_MAX / sizeof(double) before attempting your allocation.




回答2:


If you are using Visual Studio for building, you may want to enable "large memory allocation" in Linker settings.

Go to project Properties -> Linker -> System -> Enable Large Addresses set to "Yes (/LARGEADDRESSAWARE)"




回答3:


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

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



来源:https://stackoverflow.com/questions/23470003/why-am-i-getting-invalid-allocation-size-4294967295-bytes-instead-of-an-std

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!