[英]Why does attempting to return in this function cause the program to crash in C++?
我正在一個名為CodeFights的網站上解決挑戰,以幫助我學習C ++並改進編程。 一個挑戰是編寫一個程序,該程序將根據第零個元素找到特定序列的長度:
元素0:16
元素1:1 ^ 2 + 6 ^ 2 = 37
元素2:3 ^ 2 + 7 ^ 2 = 58
...
重復元素時序列結束。
該代碼應返回序列的長度:
#include <cmath>
#include <iostream>
#include <vector>
int squareDigitsSequence(int a0) {
int counter = 0; //Counts number of elements
int temp = 0; //Stores current element
std::vector<int> sequence (1); //Stores sequence
sequence[0] = a0; //Stores first element in sequence
for (int i = 0;; i++) { //Loops until sequence finishes
counter += 1; //Increments counter
temp = 0; //Resets element storage
if (a0 < 10) { //If it is only 1 digit
temp += pow(a0, 2);
}
else if (a0 < 100 && a0 > 9) { //If it is 2 digits
temp += pow(a0 / 10, 2);
temp += pow(a0 % 10, 2);
}
else { //If it is 3 digits
temp += pow(a0 % 10, 2);
temp += pow(((a0 % 100) - (a0 % 10)) / 10, 2);
temp += pow(a0 / 100, 2);
}
for (int b = 0; b < counter; b++) { //Checks if the element has appeared before
if (temp == sequence[b]) {
return counter; //Crashes here.
}
}
sequence[i + 1] = temp; //Stores current element in sequence
a0 = temp; //Moves element to be checked to current element
}
return 0; //Would not accept the function without this
}
int main() {
std::cout << squareDigitsSequence(16);
return 0;
}
嘗試運行此命令將導致程序崩潰。 我嘗試調試,並且也尋找類似的問題,但沒有成功。 幫助表示贊賞。
編輯:問題是我創建了一個大小為(1)的向量,並嘗試向其添加更多元素。 解決方案使用.push_back()代替[i + 1]。
感謝所有回答的人,希望這對將來對其他人有用。
崩潰是此行中寫越界的結果:
sequence[i + 1] = temp;
由於向量是使用大小1初始化的,並且從未調整大小,因此內部緩沖區溢出並覆蓋了一些任意的內存位置。
為避免此問題,請使用vector::push_back
,如果內部緩沖區不夠大,它將擴大矢量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.