简体   繁体   English

C ++动态布尔数组导致崩溃

[英]C++ Dynamic bool array causes crash

Today I tried to program the Sieve of Eratosthenes and it works as far as it provides me with the prime numbers. 今天,我尝试对Eratosthenes的Sieve进行编程,并且可以为我提供质数。 But I have a problem with the dynamic array I don't understand. 但是我不了解动态数组的问题。

First problem: As soon as I try to enter a "big" value for n (for example 120), the program crashes, it doesn't even allocate the memory. 第一个问题:一旦我尝试输入n的“大”值(例如120),程序就会崩溃,甚至不分配内存。

Second problem: If I enter a value like 50 it is able to give out the correct prime numbers but crashes before it deletes the array. 第二个问题:如果我输入一个类似50的值,它可以给出正确的质数,但是在删除数组之前会崩溃。

Third problem: If I enter a very small value like 5 it is able to execute the entire program, it gives out the correct numbers and deletes the memory. 第三个问题:如果我输入一个非常小的值(如5),它可以执行整个程序,它会给出正确的数字并删除内存。

But I don't understand why it acts so differently. 但是我不明白为什么它的行为如此不同。 120 boolean values can't crash my memory, at least I think so. 120个布尔值不能使我的内存崩溃,至少我认为是这样。 And why isn't it able to delete an array of 50 values but is actually able to delete an array of 5 values? 为什么它不能删除50个值的数组,但实际上却能够删除5个值的数组呢? Can anyone tell me what's the problem? 谁能告诉我这是什么问题?

int n;
cin >> n;
n=n+1;
bool *feld = new bool[n];
for(int i=2;i<n;i++)
{
    int j=i*i;
    feld[j]=true;
    for(;j<n;j+=i)
        feld[j]=true;
}
for(int i=2;i<n;i++)
    if(!feld[i])
        cout << i << endl;
    else;
delete[] feld;
feld = NULL;

Your problem is here: 您的问题在这里:

int j=i*i;
feld[j]=true;

there is no check as to whether j < n so you are stomping over unallocated memory when j >= n . 没有检查j < n是否为j < n因此当j >= n时,您将访问未分配的内存。

This code is wrong 该代码是错误的

bool *feld = new bool[n];
for(int i=2;i<n;i++)
{
    int j=i*i;
    feld[j]=true;
    ...
}

Suppose n == 10 and i == 9, then j == 81 but you only have 10 elements in your bool array. 假设n == 10且i == 9,则j == 81,但布尔数组中只有10个元素。

This is how it works when you write bugged programs, sometimes it seems to work, it might even give the right answer, other times it will crash. 当您编写有错误的程序时,这就是它的工作方式,有时它似乎可以工作,甚至可以给出正确的答案,但有时会崩溃。 This is a very important lesson, and you're actually lucky to have learned it early. 这是非常重要的一课,实际上您很幸运能早日学习。

Actually It's not just that feld[j]=true; 实际上,不仅仅是feld[j]=true; is causing the error. 导致错误。

Also, you don't need that line at all before the loop. 此外,循环之前根本不需要该行。

because, it's the first case inside the loop. 因为,这是循环内的第一种情况。

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

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