Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing memory on the heap. Should I and how?

I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it.

Here's the function I've written:

    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;
}

As I understand it, folderPath is allocated on the heap. EmptyDirectory() is my own function that removes all content in the directory. RemoveDirectory() and DeleteFile() are system calls.

My question is should I deallocate folderPath before the function exits? If I should, how do I do it?

like image 595
ageektrapped Avatar asked Jan 21 '26 21:01

ageektrapped


1 Answers

I think you want to use this:

delete [] folderPath;

It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll get a memory leak with Treb's solution.

like image 88
rmeador Avatar answered Jan 24 '26 12:01

rmeador



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!