title: C++ string compress
body: <p>I wrote a program to compress a string using the counts of repeated characters. if the compressed string is longer than the original string, then we still return the original string. Below is my program:</p>
  
  <pre><code>void stringCompress(char* src) {
      char* original;
      original = src;
      char* rst;
      rst = src;
  
      int histogram[256];
      for (int i = 0; i &lt; 256; i++) {
          histogram[i] = 0;
      }
      int length = 0;
      while (*src != NULL) {
          length++;
          src++;
      }
      src = original;
      int j = 0;
  
      for (int i = 0; i &lt; length; i++) {
  
          histogram[(int) src[i]]++;
          if (histogram[(int) src[i]] == 1) {
              rst[j] = src[i];
  
              j++;
  
          }
  
      }
      rst[j] = '\0';
  
      char* final;
  
      rst = original;
      int index = 0;
      char buffer[33];
  
      for (int i = 0; i &lt; j; i++) {
  
          final[index] = rst[i];
  
          stringstream number;
          number&lt;&lt;histogram[(int)rst[i]];
  -------&gt;        //cout&lt;&lt;number.str()&lt;&lt;endl;
          char* temp = new char[number.str().length()+1];
          strcpy(temp, number.str().c_str());
          index++;
          cout&lt;&lt;temp&lt;&lt;endl;
          for(int k =0 ;k&lt;number.str().length();k++)
          {
              final[index]=temp[k];
              index++;
  
          }
  
      }
  
      final[index] = '\0';
      src = original;
  
      if (index &lt;= length) {
          for (int i = 0; i &lt; index; i++)
  
              cout&lt;&lt;final[i];
      } else {
          cout &lt;&lt; src &lt;&lt; endl;
      }
  
  }
  </code></pre>
  
  <p>But strange thing is that if I leave the cout sentence <code>cout&lt;&lt;number.str()&lt;&lt;endl;</code> there (the arrow points to the sentence), then the output is right. For example, aaaabcdaa outputs a6b1c1d1 and aabcd outputs aabcd. However if I comment out <code>cout&lt;&lt;number.str()&lt;&lt;endl;</code>, then nothing is generated. Any help is appreciated.</p>