[Mono-dev] Embedding Mono + SWIG string return values leads to bad free

Ewen Cheslack-Postava ewencp at cs.stanford.edu
Wed Apr 23 17:16:40 EDT 2008

That's what's odd, I'm not even freeing the memory.  Mono's GC is.
The call path goes something like:

My C code -> mono_runtime_invoke -> C# methods -> SWIG C# class ->
PInvoke call returning char* -> C call to C# delegate -> C# returns a

The returned string is passed back to the SWIG C# class and used
(successfully) and then later the GC tries to collect it and fails.
The C# delegate is just something like

static string CreateString(string input) {
  return input;

I assumed what was happening was that the callback being returned to C
code for calling was handling marshalling the char* to a MonoString
and passing it into C# code and that same string was being returned
and was safe to use (since Mono allocated it).  But for some reason on
Windows its giving me the free error when the GC tries to free it.


On Wed, Apr 23, 2008 at 5:12 AM, Robert Jordan <robertj at gmx.net> wrote:
> Hi,
>  Ewen Cheslack-Postava wrote:
>  > This seems to work well on Linux and Mac OS X, but on Windows it
>  > causes an exception when the GC tries to free that same memory.  I've
>  > verified that I do in fact get a new copy of the string out at a
>  > different address from the original.  It looks like maybe the string
>  > is just being double freed.  The specific error I get (only in the
>  > Visual Studio debugger) is:
>  >
>  > HEAP[x.exe]: Invalid Address specified to RtlFreeHeap( 01E00000, 00166C78 )
>  On Windows, the char* returned by the C# method must be freed with
>  GlobalFree (). You're probable using free () which is expecting
>  that the memory was allocated from another heap.
>  This is for compatibility with MS.NET.
>  Robert
>  _______________________________________________
>  Mono-devel-list mailing list
>  Mono-devel-list at lists.ximian.com
>  http://lists.ximian.com/mailman/listinfo/mono-devel-list

More information about the Mono-devel-list mailing list