Reputation: 23
I am working through challenges on a site called CodeFights to help me learn C++ and improve my programming. One challenge was to write a program that would find the length of a specific sequence based on the zeroth element:
Element 0: 16
Element 1: 1^2 + 6^2 = 37
Element 2: 3^2 + 7^2 = 58
...
The sequence ends when an element is repeated.
This code is supposed to return the length of the sequence:
#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;
}
Attempting to run this causes the program to crash. I have attempted to debug, and also look for similar problems but no success. Help appreciated.
EDIT: The problem was that I created a vector with size (1), and tried to add more elements to it. Solution use .push_back() instead of [i + 1].
Thanks to everyone that answered, hope this can be useful to others in the future.
Upvotes: 2
Views: 111
Reputation: 22030
The crash is the result of an out-of-bound write in this line:
sequence[i + 1] = temp;
Since the vector is initialized with size 1 and never resized, you overflow the internal buffer and override some arbitrary memory location.
To avoid this problem, use vector::push_back
, which will enlarge the vector if the internal buffer isn't large enough.
Upvotes: 4