0

I had encountered an error inside for loop, if str.size() = 1 then it's throwing error as

terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create

but if str.size() is anything more than 1 then everything goes well. Also when I changed size_t to int everything goes fine. Why?

for (size_t i = str.size() - 1; i >= 0; i--)
        excess3(str[i]);

Here str is vector of string

cigien
  • 57,834
  • 11
  • 73
  • 112

2 Answers2

1

size_t is an unsigned type, so the condition i >= 0; will always evaluate to true, and the loop never ends.

Either replace i >= 0 with i != 0 (and make sure to never enter the loop with an empty vector), or change the loop variable from size_t to a signed type like int.

dxiv
  • 16,984
  • 2
  • 27
  • 49
1

size_t is unsigned. If str.size() == 1 then i is initialized to 0. the first time through the loop is ok. The second pass decrements i and makes it very large in the unsigned world. On a 32 bit system it would be 0xFFFFFFFF, which is bigger than zero of course. Try ssize_t instead of size_t. It is the signed variant. That's also why int works.

Richard Pennington
  • 19,673
  • 4
  • 43
  • 72