I am getting a bad access error while trying to find days between two dates given as a string. I found that the maximum number of days that my function will find is 1884 but I don't know why. The bad access error is in the a.find("/") function call.
Here is the code. Any help would be much appreciated, thanks.
int daysBetweenDates(string a, string b) {
if (a == b) {
return 0;
}
cout << a << endl;
int month = stoi(a.substr(0, a.find("/")));
a = a.substr(a.find("/")+1);
int day = stoi(a.substr(0, a.find("/")));
a = a.substr(a.find("/")+1);
int year = stoi(a);
int k = 0; // days in the month;
if (month == 2) {
k = year%4==0 ? 29 : 28;
}
else if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
k = 30;
}
else {
k = 31;
}
day++;
if (day > k) {
month++;
day = 1;
}
if (month > 12) {
year++;
month = 1;
}
string new_a = to_string(month) + "/" + to_string(day) + "/" + to_string(year);
return 1 + daysBetweenDates(new_a, b);
}
The recursive calls are eventually causing a stack overflow. Change the code to remove the potentially deeply nested calls. For example, by changing the routine to use a loop. C++ compilers typically do not do tail recursion optimization.