我有一大堆代码用来获取CLR DLL中映射驱动器的UNC路径,但是当我最后释放内存时,char数组会导致无效的堆指针声明失败,并且m假定它与InteropServices分配它有关,但是我想确保它不会因重复调用此函数而导致内存泄漏。

代码:

DWORD MAX_DEVICE_LENGTH = 1000;
TCHAR* szDeviceName = new TCHAR[MAX_DEVICE_LENGTH];
memset(szDeviceName, '\0', MAX_DEVICE_LENGTH);
DWORD dwResult;


char* charpath = (char*)   (void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(path->Substring(0,2));
wchar_t* tpath = new wchar_t[MAX_DEVICE_LENGTH];

memset(tpath, '\0', MAX_DEVICE_LENGTH);

DWORD dwNum = MultiByteToWideChar (CP_ACP, 0, charpath, -1, NULL, 0);
MultiByteToWideChar (CP_ACP, 0, charpath, -1, tpath, dwNum );


dwResult = WNetGetConnection(
    tpath,
    szDeviceName, &MAX_DEVICE_LENGTH);

System::String ^ str = gcnew System::String(szDeviceName);

str += path->Substring(2, path->Length-2);

delete(szDeviceName);
free(charpath); //This is where it assert-fails
delete(tpath);

return str;

这可能是我不了解的有关内存解除分配的基本知识,但是无论哪种方式都值得弄清楚。如果有帮助,如果我跳过那条线,则tpath会删除,但如果charpath断言失败,则tpath也将失败。

最佳答案

MSDN的相关评论是



因此,除了FreeHGlobal之外,没有删除/免费的方法。

09-05 07:23