title: Is it better to return a buffer, or return a properly sized string?
body: <p>I wrote a little string compression algorithm as part of an exercise (basically takes the string "aaaabbbccc" and return "a4b3c3"). Code is as follows:</p>
  
  <pre><code>char *compress(char string[])
  {
      char buffer[256];
      char *pBuffer = buffer;
  
      char* pStr = (string - 1);
      char currentCharacter = 0;
      int length = 0;
  
      while (*++pStr != 0)
      {
          currentCharacter = *pStr;
          int currentCharacterLength = 1;
  
          while ((*(pStr + 1) == currentCharacter) &amp;&amp; (*pStr != 0))
          {
              currentCharacterLength++;
              ++pStr;
          }
  
          *pBuffer++ = currentCharacter;
          *pBuffer++ = (char)currentCharacterLength;
      }
  
      (*pBuffer) = 0;
      return buffer;
  }
  </code></pre>
  
  <p>but looking at it, I'm wondering if I shouldn't create another buffer that actually fits the correct size of the returned string. Obviously, doing so would require more processing time, but would result in a tighter solution. So I'm wondering, what is the general practice on something like this. Is it better (in general) to sacrifice speed for memory, or is it better to just leave it as is?</p>
  
  <p>Or even better, is there a better way to write this solution that I'm not even aware of?</p>