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

前端 未结 3 456
广开言路
广开言路 2021-01-13 18:04

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

try {
    int n = 0;
    cin >> n;
    double *temp = new double[n];
    ...
}
cat         


        
3条回答
  •  遥遥无期
    2021-01-13 18:28

    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.

提交回复
热议问题