How to clean up memory leak in unmanage code?
Dear All,
How to clean up memory leak in unmanage code?
I have unmanage code as below:
Code:
//API declaration's
[System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "lstrcpyA")]
private static extern int StringCchCopy(int lpstring1, int lpstring2);
[System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "lstrcpyA")]
private static extern int StringCchCopy(byte[] lpstring1, int lpstring2);
[System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "lstrcpyA")]
private static extern int StringCchCopy(string lpstring1, string lpstring2);
[System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "lstrlenA")]
private static extern int lstrlen(int lpString);
public string getStrFromPtr(int StrPointer)
{
string EndBuffer = "";
byte[] StrBuffer;
try
{
int strLen;
strLen = lstrlen(StrPointer);
StrBuffer = new byte[strLen + 1];
if (strLen > 0)
{
StringCchCopy(StrBuffer, StrPointer);
}
for (int i = 0; i < strLen; i++)
{
EndBuffer += System.Convert.ToChar(StrBuffer[i]);
}
}
catch (Exception ex) { SaveErrorLog("ClsMain.getStrFromPtr: " + ex.ToString()); }
finally { StrBuffer = null; }
return EndBuffer;
}
Re: How to clean up memory leak in unmanage code?
You pass in an unmanaged string pointer to that procedure which means that procedure is not responsible for releasing that string. Do you have the code that creates that unmanaged string ? If so can you post it ?
Re: How to clean up memory leak in unmanage code?
I also dont see any IDisposible interface/pattern...
Re: How to clean up memory leak in unmanage code?
try deleaker or similar debugger... :)
Re: How to clean up memory leak in unmanage code?
Presumably you can use the Marshal class to clean up the unmanaged memory pointed to by "StrPointer". Either that or use PInvoke to get the "VirtualFree" api, then just call it and pass your pointer in with 0x8000 as the attributes.
Re: How to clean up memory leak in unmanage code?
Also, you can always use programs for catching memory leaks. VLD is popular now.
Re: How to clean up memory leak in unmanage code?
The GC doesn't clean up any unmanaged resources, thus why implementing the IDisposable interface on a class object you have can be very useful for disposing of those objects manually.