程序出現運行時錯誤
問題描述
#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文檔怎么查看?2. javascript - 有適合開發手機端Html5網頁小游戲的前端框架嗎?3. javascript - axios請求回來的數據組件無法進行綁定渲染4. javascript - JS變量被清空5. java - 在用戶不登錄的情況下,用戶如何添加保存到購物車?6. python - Pycharm的Debug用不了7. html - eclipse 標簽錯誤8. python - pandas按照列A和列B分組,將列C求平均數,怎樣才能生成一個列A,B,C的dataframe9. 安全性測試 - nodejs中如何防mySQL注入10. javascript - 關于apply()與call()的問題
