我正在为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 吗?如果我应该,我该怎么做?

有帮助吗?

解决方案

我想你想用这个:

delete [] folderPath;

看起来你正在分配一个TCHAR数组,这是有意义的,因为它是一个字符串。分配数组时,必须使用数组删除运算符(通过在delete语句中包含括号来获取)进行删除。我很确定你会在Treb的解决方案中出现内存泄漏。

其他提示

我对那些不习惯C / C ++编程的人有一种常见的误解 - 当他们看到一个带有指针参数的函数时,他们认为该变量必须用 new 进行分配。情况并非如此,局部变量是合适的,也是首选,因为您不必担心它的生命周期。

您可以通过

极大地简化您的生活
TCHAR folderPath[256];

我首选的解决方案是使用std :: string,但我把它放在一个单独的答案中。

是的,你应该释放记忆。你调用的所有函数都不会为你做,也不应该 - 它没有任何意义。内存使用向量new运算符分配,因此应使用向量删除运算符释放,即:

delete [] folderPath;

通常最好使用std :: string,或者在你的情况下使用std :: basic_string。在这种情况下,当最终路径大于256个字符时,它会消除潜在的缓冲区溢出。

    Uninstall_Init(
    HWND        hwndParent,
    LPCTSTR     pszInstallDir
)
{
    std::basic_string<TCHAR> folderPath = pszInstallDir;
    folderPath.append(_T("\\cache"));
    EmptyDirectory(folderPath.c_str());
    RemoveDirectory(folderPath.c_str());
    folderPath = pszInstallDir;
    folderPath.append(_T("\\mobileadmin.dat"));
    DeleteFile(folderPath.c_str());
// To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE
// If you want to cancel installation,
// return codeUNINSTALL_INIT_CANCEL
return codeUNINSTALL_INIT_CONTINUE;
}

是的,你应该。致电

 delete[] folderPath;

在你的功能结束时。必须使用 delete 释放分配有 new 的所有内存。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top