程序出現運行時錯誤
問題描述
#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. python - 獲取到的數據生成新的mysql表2. javascript - js 對中文進行MD5加密和python結果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. 為什么python中實例檢查推薦使用isinstance而不是type?
