Bug? Marshaller doesn't free() strings returned by unmanaged functions

  • Thread starter Thread starter Steven Brown
  • Start date Start date
S

Steven Brown

Hello, the documentation for string marshalling[1] says that the runtime
will free the memory of strings returned by unmanaged functions, like in:

[DllImport("...")]
extern string foo();

The TestStringAsResult example[2] also dynamically allocates the
returned string as if in preparation for this. Thing is, the .NET 1.1
runtime doesn't free it. That example will leak memory.

So, which is right, the documentation, or the runtime? I'd say the
runtime, as it'd just be amazingly stupid to code it as in the
documentation, as it fails in cases where the string is read-only, on
the stack, a COM object, from a different allocator, etc., and with
functions like strcpy, strdup, strerror, etc., so you'd be stuck
returning it as IntPtr and doing a PtrToString.. in pretty much all
cases. Anyone know which is the way it's supposed to be?

[1]
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbufferssample.asp
[2]
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconpinvokelibdll.asp
 
Steven,
The TestStringAsResult example[2] also dynamically allocates the
returned string as if in preparation for this. Thing is, the .NET 1.1
runtime doesn't free it. That example will leak memory.

Really? Last time I tried it it worked fine. How do you tell it's
leaking?

So, which is right, the documentation, or the runtime? I'd say the
runtime, as it'd just be amazingly stupid to code it as in the
documentation, as it fails in cases where the string is read-only, on
the stack, a COM object, from a different allocator, etc., and with
functions like strcpy, strdup, strerror, etc., so you'd be stuck
returning it as IntPtr and doing a PtrToString.. in pretty much all
cases. Anyone know which is the way it's supposed to be?

Well the runtime assumes the memory was allocated with CoTaskMemAlloc
and therefore frees it with CoTaskMemFree. If you use any other
allocation API, you have to switch to an IntPtr return type. If the
string is stack allocated, you shouldn't return a pointer to it at
all.



Mattias
 
Mattias said:
Steven,

The TestStringAsResult example[2] also dynamically allocates the
returned string as if in preparation for this. Thing is, the .NET 1.1
runtime doesn't free it. That example will leak memory.


Really? Last time I tried it it worked fine. How do you tell it's
leaking?

Nevermind, I found it's calling CoTaskMemFree which doesn't free (or
even corrupt, apparently) malloced memory. :P
 
Back
Top