0

I have the following test program:

#include <string>
int main(int argc, char* argv[]) {
    try {
        return std::stoi("3000127232");
    }
    catch (...) {
        return 0;
    }
}

When I compile this on ubuntu with C++11 and run the code I get a return value of 0. This is what I expect because the value in the string is out of range.

But when I compile it for a rasperry-buildroot 18.11 I can run the program on rasperry, but I get a segfault. This I don't expect.

Is there another solution to convert strings to ints (without segfaults when out of range), or does anyone have another idea?

Teddy
  • 993
  • 10
  • 20

2 Answers2

1

std::stoi is specified to throw an exception if the value is out of range. If the implementation fails to do that, then it doesn't conform to the standard. This may be a compiler bug.

If for example you target a system that doesn't support exceptions or is for some other reason non-conformant, there are other ways to convert a string to an integer that don't use exceptions, such as std::strtol.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

You may want to check size of int on your raspberry, it probably gets out of range.

lmilunovic
  • 191
  • 1
  • 10