title: C++ Converting binary data to a hex string and back
body: <p>I have a matching pair of static functions in a utility class that I use to convert between binary data (unsigned characters) and it's string representation (a-f and 0-9). They seemed to work correctly but recently I tried to compile my code under Visual C++ (2010 Express) and to my dismay, they cause nothing but heap corruption errors. What am I doing wrong?</p>
  
  <pre><code>void Utility::string_to_binary(const std::string source, unsigned char* destination, unsigned int length)
  {
      unsigned int effective_length = min(length, (unsigned int) source.length() / 2);
      for(unsigned int b = 0; b &lt; effective_length; b++)
      {
          sscanf(source.data() + (b * 2), "%02x", (unsigned int*) &amp;destination[b]);
      }
  }
  
  void Utility::binary_to_string(const unsigned char* source, unsigned int length, std::string&amp; destination)
  {
      destination.clear();
      for(unsigned int i = 0; i &lt; length; i++)
      {
          char digit[3];
          sprintf(digit, "%02x", source[i]);
          destination.append(digit);
      }
  }
  </code></pre>
  
  <p><strong>Edit: Here's a complete program that illustrates the problem.</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;hdcs/Utility.h&gt;
  
  using namespace std;
  
  int main(int argc, char* argv[])
  {
      //Generate some data
      unsigned int size = 1024;
      unsigned char* data = new unsigned char[size];
  
      //Convert it to it's string representation
      string hex;
      Utility::binary_to_string(data, size, hex);
  
      //Output it to the screen
      cout &lt;&lt; hex &lt;&lt; endl;
  
      //Clear the data buffer
      memset(data, 0, sizeof(unsigned char) * size);
  
      //Convert the hex string back to binary
      Utility::string_to_binary(hex, data, size);
  
      //Cleanup
      delete[] data;
  }
  </code></pre>
  
  <p>The error occurs on <code>delete[] data</code>.</p>