Why does this code cause an out_of_range error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Why does this code cause an out_of_range error?

https://code.sololearn.com/csGBIZ4Qy7gs/#cpp If you enter a range above 65535, the substr()-function will cause an out_of_range error. 66535 is the maximum value of a uint16_t, so my guess is that somewhere, either in the string or in the substr()-function, this datatype is being used. Can anyone explain? Thanks in advance!

26th Feb 2018, 12:18 AM
Chris
Chris - avatar
2 Answers
+ 9
Replacing function args type and variable square type with long long int appears to fix the issue. I believe 66535 caused an overflow which happens to mess with either stringstream or/then substr. And yes. Further inspection says that your code here: string compare = square_str.substr(square_str.length()-number_str.length(), number_str.length()); assumes that square_str.length() will always be larger than number_str.length(), which is untrue for cases of overflow.
26th Feb 2018, 12:45 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Oh, of course! Overflow makes perfect sense, as the square of 2^16 (= 2^32) is outside the range of int. Thank you very much!
26th Feb 2018, 3:57 PM
Chris
Chris - avatar