Marshal.PtrToStringAnsi() Memory Leak? Options

S

sabys

I've been noticing a memory leak with the following sample code
snippet. Can someone please advise.

Have a C# Winforms app with the following code on a button-click
event.

private void button1_Click(object sender, System.EventArgs e)
{
IntPtr p1 = new IntPtr(-1);
string inputStr;
AllocString(out p1); //AllocString() called via Interop
string managedStr = Marshal.PtrToStringAnsi(p1);
Thread.Sleep(20);
Marshal.FreeHGlobal(p1);
}

The method AllocString() is defined in a C-DLL as:
CDLL_API void AllocString(char** inputStr)
{
int len = 10000000;
char * x = (char *) GlobalAlloc(0, len+1);
memset(x,65,len);
x[l]=0;
*inputStr = x;
}


On launching the application, the steady state private bytes is 10MB.

On clicking the button, I see private bytes increase to 30MB. Why the
additional overhead of 20MB for PtrToStringAnsi()? And this 20MB is
never freed. Also confirmed that the bytes allocated are in the
unmanaged heap, since the .NET "# Bytes in All Heaps" never
increases.

If I comment the Marshal.PtrToStringAnsi() line, private bytes always
comes back to 10MB.

Is this expected behavior for Marshal.PtrToStringAnsi() ? (.NET
Framework 1.1)
 
W

Willy Denoyette [MVP]

I've been noticing a memory leak with the following sample code
snippet. Can someone please advise.

Have a C# Winforms app with the following code on a button-click
event.

private void button1_Click(object sender, System.EventArgs e)
{
IntPtr p1 = new IntPtr(-1);
string inputStr;
AllocString(out p1); //AllocString() called via Interop
string managedStr = Marshal.PtrToStringAnsi(p1);
Thread.Sleep(20);
Marshal.FreeHGlobal(p1);
}

The method AllocString() is defined in a C-DLL as:
CDLL_API void AllocString(char** inputStr)
{
int len = 10000000;
char * x = (char *) GlobalAlloc(0, len+1);
memset(x,65,len);
x[l]=0;
*inputStr = x;
}


On launching the application, the steady state private bytes is 10MB.

On clicking the button, I see private bytes increase to 30MB. Why the
additional overhead of 20MB for PtrToStringAnsi()? And this 20MB is
never freed. Also confirmed that the bytes allocated are in the
unmanaged heap, since the .NET "# Bytes in All Heaps" never
increases.

If I comment the Marshal.PtrToStringAnsi() line, private bytes always
comes back to 10MB.

Is this expected behavior for Marshal.PtrToStringAnsi() ? (.NET
Framework 1.1)


Please, don't multipost, this same question of yours has been answered in
the interop NG.

Willy.
 

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