程序出现运行时错误
问题描述
#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中还会弹出一个窗口,提示源 源未知 不可用
请问问题出在哪里了?谢谢了
问题解答
回答1:通常win平台非预期的sigtrap都是heap corruption。再看你的代码,第十六行arr[j] = 1; 明显有invalid write。所以vector arr(n, 0);的n应该改大一点,比如n+1。
相关文章:
1. js怎样实现在类似qq的联系人分组中进行搜索后,又可恢复原分组的界面?2. python - 如何获取rabbitmq连接的celery的个数3. 上传多图时,最后一张图为缩略图,想设置第一张图为缩略图怎么解决?4. python 中文乱码问题5. javascript - 百度地图一开始设置了中心点,怎么通过按钮在调转到对应的中心点????6. python - 如何将文本文件的CR换行符换成LF换行符?7. Mysql: FIND_IN_SET 的反运算8. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。9. mysql优化 - mysql 一张表如果不能确保字段列长度一致,是不是就不需要用到char。10. 怎样用python给mp3添加封面?