I want to allocate and deallocate memory in unmanaged code (C++) and we call them functions from managed code (C#). Iam not sure whether the following code is fine without memory leaks or not?
C# code:
[DllImport("SampleDLL.dll")]
public extern void getString([MarshalAs(UnmanagedType.LPStr)] out String strbuilder);
[DllImport("SampleDLL.dll")]
public extern void freeMemory([MarshalAs(UnmanagedType.LPStr)] out String strBuilder);
....
//call to unmanaged code
getString(out str);
Console.WriteLine(str);
freeMemory(out str);
C++ code:
extern void _cdecl getString(char **str)
{
    *str = new char[20];
    std::string temp = "Hello world";
    strncpy(*str,temp.c_str(),temp.length()+1);
}
extern void _cdecl freeMemory(char **str)
{
    if(*str)
        delete []*str;
    *str=NULL;
}
 
     
     
    