[英]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.