Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 999
scbeacham Avatar asked Nov 27 '13 23:11

scbeacham


3 Answers

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!

like image 178
templatetypedef Avatar answered Oct 07 '22 11:10

templatetypedef


If you have 9 bones, you should only print 8 connections, not 9. On the last one you reference bone[8] & bone[9]. bone[9] does not exist.

like image 39
woolstar Avatar answered Oct 07 '22 12:10

woolstar


Similar error:

I had count as -1 when below statement was executed:

cout << string(count, ' ') << "main - end " << endl;

string(count, ' ') creates a string of spaces of length count but since count is -ve, it fails to create.

So basically it can fail for any other library function, careful writing code & careful debugging can help.

like image 32
Manohar Reddy Poreddy Avatar answered Oct 07 '22 12:10

Manohar Reddy Poreddy