search

Home  >  Q&A  >  body text

c++ - 程序出现运行时错误

#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>

using namespace std;
int countPrimes(int n) {
    if (n <= 2)
        return 0;
    vector<int> arr(n, 0);
    for (int i = 2; i <= sqrt(n); ++i)
    {
        if (!arr[i])
            for (int j = i * i; j <= n; j += i)
            {
                arr[j] = 1; 
            }
    }
    cout << arr[2] << endl;
    int j = 0;
    for (int i = 2; i <= n; ++i)
    {
        if (!arr[i])
        {
            arr[j++] = i;
        } 
    }
    cout << "j" << j << endl;
    int l = 0, r = j - 1;
    while (l <= r)
    {
        int m = (l + r) >> 1;
        cout << m << endl;
        cout << "arr[m]" << arr[m] << "n - 1" << n - 1 << endl;
        if (arr[m] == n - 1)
        {
            l = r = m;
            return l + 1;
        }
        else if (arr[m] < n - 1)
        {
            l = m + 1;
        }
        else
            r = m - 1;
        cout << "l = " << l << "r= " << r << endl;
        cout << "m=" << m << endl;
    }
    cout << l << endl;
    return 0;
}

int main()
{
    cout << countPrimes(6) << endl;

    return 0;
}

在程序中加断点,发现运行到return l + 1处时报错,报错信息如下

在VSCODE中还会弹出一个窗口,提示源 源未知 不可用

请问问题出在哪里了?谢谢了

阿神阿神2803 days ago559

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:50:13

    Usually unexpected sigtraps on the win platform are heap corruption.
    Looking at your code again, line 16 arr[j] = 1; obviously contains invalid write.
    So the vector<int> arr(n, 0); of n should be changed to a larger size, such as n+1.

    reply
    0
  • Cancelreply