为什么我会收到"无效的分配大小:4294967295字节"代替的std :: bad_alloc异常? [英] Why am I getting "Invalid Allocation Size: 4294967295 Bytes" instead of an std::bad_alloc exception?

查看:479
本文介绍了为什么我会收到"无效的分配大小:4294967295字节"代替的std :: bad_alloc异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面一段code的分配为一个数组的内存:

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);
}

当然,我检查阴性n值等等。但是当我输入一些大量在536 *(10的6次方)我没有得到一个坏的alloc异常,但一个无效的分配大小:4294967295字节崩溃。

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.

例如。我输入n = 536 *(10 ^ 6) - >坏ALLOC异常
我输入n = 537 *(10 ^ 6) - >无效的分配大小:4294967295字节 - >崩溃

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?

推荐答案

调用新的双[N] 呼吁全球运营商新的,大小 N * sizeof的功能(双)。如果运营商新的然后发现它不能满足要求,它抛出一个异常。

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.

不过,这不能发生在这里:该产品 N 的sizeof(双)是如此之大,它实际上是不可能叫运营商新的可言,因为你要求的只是普通的不适合在为size_t 。在实现他们是如何处理这个问题各不相同,但你显然会中止程序。

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.

如果你想解决这个问题,你可以检查 N'LT; = SIZE_MAX /的sizeof(双)尝试之前你分配

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

这篇关于为什么我会收到&QUOT;无效的分配大小:4294967295字节&QUOT;代替的std :: bad_alloc异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆