title: terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create
body: <p>I am getting runtime error mentioned in the title when compiler is in release version and segfault when it is in debug version. I did some research and all I found that it is because of the way I am passing strings to add method. I am not clear so it would great help if anyone describe in simple words why runtime error is occurring.</p>
  
  <pre><code>#include &lt;bits/stdc++.h&gt;
  using namespace std;
  string add(string a,string b)
  {
  
  int lena=a.size()-1,lenb=b.size()-1,carry=0,t;
  //segfault occurs here 
  string tmp;
  int m,n;
  while(lena&gt;=0||lenb&gt;=0)
  {
      m=0;
      n=0;
      if(lena&gt;=0)
      {
          m=a[lena]-'0';
          lena--;
      }
      if(lenb&gt;=0)
      {
          n=b[lenb]-'0';
          lenb--;
      }
      t=m+n+carry;
      if(t&gt;9)
      {
          carry=1;
      }
      else
      carry=0;
      tmp.push_back('0'+t%10);
  }
  if(carry)
  tmp.push_back('1');
  reverse(tmp.begin(),tmp.end());
  return tmp;}
  
  class Solution
  {
  public:
  string multiply(string A,string B);
  };
  
  string Solution::multiply(string A,string B) {
      int i=A.size()-1,j=0,szb=B.size(),c=0,m=0,k=0,n=0;
      string sum="",tmp="";
      while(i&gt;=0)
      {
          tmp.clear();
          j=szb-1;
          k=n;
          while(k--)
          {
              tmp.push_back('0');
          }
          n++;
          c=0;
          while(j&gt;=0)
          {
              m=(A[i]-'0')*(B[j]-'0')+c;
              c=m/10;
              tmp.push_back((m%10)+'0');
              j--;
          }
          if(c)
          tmp.push_back(c+'0');
          reverse(tmp.begin(),tmp.end());
          sum=add(sum,tmp);
          i--;
      }
      string ans;
      for(i=0,j=sum.size();i&lt;j;i++)
      {
          if(sum[i]!='0')
          {
              while(i&lt;j)
              {
                  ans.push_back(sum[i]);
                  i++;
              }
          }
      }
      if(ans.size()==0)
      return "0";
  }
  
  int main()
  {
      Solution ob;
      string  s;
      s=ob.multiply("99999","99999");
      cout&lt;&lt;s&lt;&lt;endl;
  }
  </code></pre>