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

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
 
M

Mattias Sjögren

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
 
S

Steven Brown

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top