title: C++ MFC: Memory Leak When Creating CString From Char*
body: <p>I am getting a memory leak when I run try to read from Clipboard.</p>
  
  <p>Sample code:  </p>
  
  <pre><code>void SomeFunction()
  {
     OpenClipboard(nullptr);
     HGLOBAL hglb = GetClipboardData(CF_TEXT);
     char* ch = static_cast&lt;char*&gt;(GlobalLock(hglb));
  
     CString rawClipboardData(ch);
  
     GlobalUnlock(hglb);
     CloseClipboard();
  }
  </code></pre>
  
  <p>It is the middle row above which causes the memory leak according to Visual Studio. This row:</p>
  
  <pre><code>CString rawClipboardData(ch);
  </code></pre>
  
  <p>If I do not run it, there is no leak reported.
  But if I do run it I get the following debug output in visual studio output window:</p>
  
  <pre><code>Detected memory leaks!
  Dumping objects -&gt;
  f:\dd\vctools\vc7libs\ship\atlmfc\src\strcore.cpp(158) : {75645} normal block at 0x00000000072C89A0, 52 bytes long.
  Data: &lt;`x              &gt; 60 78 F7 D3 FE 07 00 00 0D 00 00 00 0D 00 00 00
  Object dump complete.
  </code></pre>
  
  <p>Any ideas?</p>
  
  <p>UPDATE: Added OpenClipboard(nullptr) in code above. Also in real code there are nullptr-checks. Just keeping it clean here to reduce amount of guard-clause code.</p>