我正在为 Windows Mobile 应用程序编写 CESetup.dll。它必须是不受管理的,我对此没有什么经验。所以我不确定是否应该释放分配的内存以及如何释放。
这是我写的函数:
Uninstall_Init(
HWND hwndParent,
LPCTSTR pszInstallDir
)
{
LPTSTR folderPath = new TCHAR[256];
_stprintf(folderPath, _T("%s\\cache"), pszInstallDir);
EmptyDirectory(folderPath);
RemoveDirectory(folderPath);
_stprintf(folderPath, _T("%s\\mobileadmin.dat"), pszInstallDir);
DeleteFile(folderPath);
// To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE
// If you want to cancel installation,
// return codeUNINSTALL_INIT_CANCEL
return codeUNINSTALL_INIT_CONTINUE;
}
据我了解,folderPath 是在堆上分配的。 EmptyDirectory() 是我自己的函数,用于删除目录中的所有内容。 RemoveDirectory() 和 DeleteFile() 是系统调用。
我的问题是我应该在函数退出之前释放 folderPath
吗?如果需要,我该怎么做?
最佳答案
我在不习惯 C/C++ 编程的人身上看到了一个常见的误解 - 当他们看到带有指针参数的函数时,他们认为变量必须用 new 分配。事实并非如此,局部变量是合适且首选的,因为您不必担心它的生命周期。
你可以通过这样做极大地简化你的生活
TCHAR folderPath[256];
我的首选解决方案是使用 std::string,但我已将其放在单独的答案中。
关于c++ - 释放堆上的内存。我应该和如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/240184/