简体   繁体   English

C ++奇怪的std :: bad_alloc异常

[英]C++ Strange std::bad_alloc exception

So I have the following code: 所以我有以下代码:

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const int MAXN = 1000000;
int isNotPrime[MAXN];
vector<int> primes;

void sieve()
{
    for(int i = 2; i <= sqrt(MAXN); ++i)
    {
        if(isNotPrime[i]) continue;
        for(int j = i*i; j <= MAXN; j += i)
        {
            isNotPrime[j] = true;
        }
    }
    for(int i = 2; i <= MAXN; ++i)
    {
        if(!isNotPrime[i])
        {
            primes.push_back(i);
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    sieve();
    return 0;
}

What I cannot understand is why my program throws a std::bad_alloc exception when it executes. 我不明白的是为什么我的程序在执行时会抛出std :: bad_alloc异常。 Even more mind-boggling is that when I swap the lines int isNotPrime[MAXN]; 更让人难以置信的是,当我交换行int isNotPrime[MAXN]; and vector<int> primes; vector<int> primes; the programs executes as intended. 程序将按预期执行。 Swapped like this: 像这样交换:

vector<int> primes;
int isNotPrime[MAXN];

The problem is here: 问题在这里:

for(int i = 2; i <= MAXN; ++i)

The check should be i < MAXN instead. 支票应为i < MAXN (Or, make the array have size MAXN + 1 .) (或者,使数组的大小为MAXN + 1

At some point, the isNotPrime[MAXN] = true; 在某个时候, isNotPrime[MAXN] = true; executes, which overflows the bounds of the array, causing undefined behaviour . 执行,将溢出数组的边界,从而导致未定义的行为 In practice, this overwrites some internal field of the next variable ( primes ), which confuses the std::vector implementation, probably causing it to request a lot of memory. 在实践中,这将覆盖下一个变量( primes )的某些内部字段,这会使std::vector实现混乱,可能导致其请求大量内存。

This also explains why switching the variable order "fixes" it, because now you're scribbling over something else instead of primes . 这也解释了为什么切换可变顺序可以“修复”它,因为现在您是在乱写其他东西而不是primes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM