Understanding error "terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create Aborted (core dumped)"

scbeacham picture scbeacham · Nov 28, 2013 · Viewed 61.5k times · Source

So here is my error:

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create
Aborted (core dumped)

and here is my code:

//Code removed

string generateSong(string list[], int num)
{
   //Code removed

   //Code removed

   for (i = 0; i < num; i++)
   {
      output += list[i];
      output += bone1;
      output += list[i + 1];
      output += bone2;
   }

   return output;
}

int main()
{
   string list[9] =
   {

   //Code removed

   };

   //Code removed

   return 0;
}

I would just like to know what that error means so I know how to fix it. I've seen many posts with similar errors but nothing exactly the same. I am literally just starting out in C++, and none of those answers make sense with what I have learned so far. As you can see this is a simple program to output a song. It's meant to help me practice strings for the class I'm taking, but it makes absolutely no sense to me and the book isn't much help either. Could someone please explain this to me?

P.S. In case this is helpful, it will compile using g++, but when it runs it gives that error (so basically it's not a compile error, it's a run error).

Answer

templatetypedef picture templatetypedef · Nov 28, 2013

This part of the code is suspicious:

 for (i = 0; i < num; i++)
 {
    output += list[i];
    output += bone1;
    output += list[i + 1]; // <--- here
    output += bone2;
 }

Your array has length 9, so the valid indices in it range from 0, 1, 2, ..., 8. On iteration 8, the indicated line will try to read array index 9, which isn't valid. This results in undefined behavior, which in your case is a misleading error message about an invalid string.

You'll have to decide what steps you'll want to take to fix this, but I believe this is the immediate cause of the problem.

Hope this helps!