title: Release unmanaged memory from managed C# with pointer of it
body: <p>The question in short words is :
  How to free memory returned from Native DLL as ItrPtr in managed code?</p>
  <p>Details :
  Assume we have simple function takes two parameters as OUTPUT, The first one is Reference Pointer to byte array and the second one is Reference Int .
  The function will allocate amount of bytes based on some rules and return the pointer of memory and the size of bytes and the return value (1 for success and 0 for fail) .</p>
  <p>The code below works fine and I can get the byte array correctly and the count of bytes and the return value, but when I try to free the memory using the pointer (IntPtr) I get exception :</p>
  <blockquote>
  <p>Windows has triggered a breakpoint in TestCppDllCall.exe.</p>
  <p>This may be due to a corruption of the heap, which indicates a bug in TestCppDllCall.exe or any of the DLLs it has loaded.</p>
  <p>This may also be due to the user pressing F12 while TestCppDllCall.exe has focus.</p>
  <p>The output window may have more diagnostic information.</p>
  </blockquote>
  <p>To make things clear :</p>
  <ol>
  <li><p>The next C# code work correctly with other DLL function have the same    signature and freeing the memory works without any problem .</p>
  </li>
  <li><p>Any modification in (C) code accepted if you need to change allocation memory method or adding any other code .</p>
  </li>
  <li><p>All the functionality I need is Native DLL function accept Two Parameter by reference (Byte array and int , In c# [IntPtr of byte array and int]) fill them with some values based on some rules and return the function result (Success or Fail) .</p>
  </li>
  </ol>
  <hr />
  <p><strong>CppDll.h</strong></p>
  <pre><code>#ifdef CPPDLL_EXPORTS
  #define CPPDLL_API __declspec(dllexport)
  #else
  #define CPPDLL_API __declspec(dllimport)
  #endif
  
  extern &quot;C&quot; CPPDLL_API int writeToBuffer(unsigned char *&amp;myBuffer, int&amp; mySize);
  </code></pre>
  <p><strong>CppDll.cpp</strong></p>
  <pre><code>#include &quot;stdafx.h&quot;
  #include &quot;CppDll.h&quot;
  
  extern &quot;C&quot; CPPDLL_API int writeToBuffer(unsigned char*&amp; myBuffer, int&amp; mySize)
  {
      mySize = 26;
  
      unsigned char* pTemp = new unsigned char[26];
      for(int i = 0; i &lt; 26; i++)
      {
          pTemp[i] = 65 + i;
      }
      myBuffer = pTemp; 
      return 1;
  }
  </code></pre>
  <p><strong>C# code :</strong></p>
  <pre><code>using System;
  using System.Text;
  using System.Runtime.InteropServices;
  
  namespace TestCppDllCall
  {
      class Program
      {
          const string KERNEL32 = @&quot;kernel32.dll&quot;;
          const string _dllLocation = @&quot;D:\CppDll\Bin\CppDll.dll&quot;;
          const string funEntryPoint = @&quot;writeToBuffer&quot;;
  
          [DllImport(KERNEL32, SetLastError = true)]
          public static extern IntPtr GetProcessHeap();
          [DllImport(KERNEL32, SetLastError = true)]
          public static extern bool HeapFree(IntPtr hHeap, uint dwFlags, IntPtr lpMem);
          [DllImport(_dllLocation, EntryPoint = funEntryPoint, CallingConvention = CallingConvention.Cdecl)]
          public static extern int writeToBuffer(out IntPtr myBuffer, out int mySize);
  
          static void Main(string[] args)
          {
              IntPtr byteArrayPointer = IntPtr.Zero;
              int arraySize;
              try
              {
                  int retValue = writeToBuffer(out byteArrayPointer, out arraySize);
                  if (retValue == 1 &amp;&amp; byteArrayPointer != IntPtr.Zero)
                  {
                      byte[] byteArrayBuffer = new byte[arraySize];
                      Marshal.Copy(byteArrayPointer, byteArrayBuffer, 0, byteArrayBuffer.Length);
                      string strMyBuffer = Encoding.Default.GetString(byteArrayBuffer);
                      Console.WriteLine(&quot;Return Value : {0}\r\nArray Size : {1}\r\nReturn String : {2}&quot;,
                          retValue, arraySize, strMyBuffer);
                  }
              }
              catch (Exception ex)
              {
                  Console.WriteLine(&quot;Error calling DLL \r\n {0}&quot;, ex.Message);
              }
              finally
              {
                  if (byteArrayPointer != IntPtr.Zero)
                      HeapFree(GetProcessHeap(), 0, byteArrayPointer);
              }
              Console.ReadKey();
          }
      }
  }
  </code></pre>
  <p>When I debug this code i set break point in the line (return 1) and the value of the buffer was :</p>
  <pre><code>myBuffer = 0x031b4fc0 &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ‎‎‎‎««««««««î‏&quot;
  </code></pre>
  <p>And I got the same value in C# code when the function call return and the value was :</p>
  <pre><code>52121536
  </code></pre>
  <p>The result I Got the correct Memory pointer and i am able to get the byte array value , how to free these memory blocks with this pointer in C# ?</p>
  <p>Please let me know if there anything is not clear or if there any typo, I am not native English speaker .</p>