c++ - 释放堆上的内存。我应该和如何?

标签 c++ winapi memory-management windows-ce

我正在为 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/

相关文章:

c++ - 文件C++中的字符交换

c++ - 宏 菜鸟程序员

c - 在 C 中使用带有 sendInput 的鼠标

iphone - 将指针设置为 nil,objective-c

c++ - 你如何处理内存管理和信号/插槽?

c++ - const cast 和 std launder

c++ - LNK2019 : Unresolved external when calling to a function in a C dll from a C++ console Application (no CLR)

c++ - 从外部应用程序附加子窗口时的消息循环(泵)

c - WM_TIMER 在特定条件下丢失

c++ - 动态数组分配末尾的()是什么意思?