title: c++ string has garbage chars
body: <p>I'm just getting in to c++ and I was working on a base 62 convertor program. It works just fine for the long to string function and for the string to long function as long as the string is under 4 chars long. Then things just get weird.  </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;math.h&gt;
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int char_to_int(char a){
      int b=(int)a;
      if(b-(int)'0'&gt;=0&amp;&amp;b-(int)'0'&lt;10)
          return b-(int)'0';
      if(b-(int)'a'&gt;=0&amp;&amp;b-(int)'a'&lt;26)
          return b-(int)'a'+10;
      return b-(int)'A'+36;
  }
  
  char int_to_char(int a){
      if(a&lt;10)
          return (char)(a+(int)'0');
      if(a&lt;36)
          return (char)((a-10)+(int)'a');
      return (char)((a-36)+(int)'A');
  };
  
  long stol(string a){
      int length=a.size()-1;
      int power=0;
      long total=0;
      for(;length&gt;=0;length--){
          total+=(char_to_int(a[length])*(long)pow(62,power));
          power++;
      }
      return total;
  }
  
  string ltos(long a){
      int digits=(int)(log(a)/log(62))+1;
      char pieces[digits];
      int power=digits-1;
      for(int i=0;i&lt;digits;i++){
          pieces[i]=int_to_char((int)(a/pow(62,power)));
          cout&lt;&lt;pieces[i]&lt;&lt;endl;
          a=a%(long)pow(62,power);
          power--;
      }
      return string(pieces);
  }
  
  int main(){
      string secret_password="test";
      long pass_long=stol(secret_password);
      string to_out=ltos(pass_long);
      cout&lt;&lt;sizeof(to_out)&lt;&lt;endl;
      cout&lt;&lt;to_out&lt;&lt;endl;
      cout&lt;&lt;to_out[4]&lt;&lt;endl;
      cout&lt;&lt;to_out[5]&lt;&lt;endl;
      cout&lt;&lt;to_out[6]&lt;&lt;endl;
  }
  </code></pre>
  
  <p>The output is as follows:  </p>
  
  <pre><code>t
  e
  s
  t
  4
  test═ôZAx■(
  ═
  ô
  Z
  </code></pre>
  
  <p>As you can see, there's a bunch of garbage at the end. I'm confused because I know the length of the string is 4, but the next couple characters are printed as well. I just started c++ and have only worked with Java until now, and I know there are some nuances with strings in c++. It may have something to do with that, or it might just have something to do with type conversion.</p>