views:

271

answers:

2

Hi

Suppose i have a LPSTR variable. How do i free the memory after using the variable. Is it

LPSTR szFileName = GetSBCSBuffer(sFilePath); // sFilePath is a CString
delete szFileName;

OR

delete []szFileName;

Kindly advise

+1  A: 

If memory was allocated using new char[SIZE] then it needs to be freed using delete [].

elder_george
i dont explicitly allocate all i do is written in that code where getsbcsbuffer() function accepts a string and returns a char * something like this int len = WideCharToMultiByte(CP_ACP, 0, str, -1, 0, 0, 0, 0); // allocate the buffer to hold the converted string LPSTR result = new char[len]; // do the conversion WideCharToMultiByte(CP_ACP, 0, str, -1, result, len, 0, 0); return result;
ckv
+1  A: 

You can't answer that question without knowing the specifics of GetSBCSBuffer. Hopefully whoever wrote the function left you with code and/or documentation so you can see where the string comes from. It might be that neither of your alternatives is correct. The author of GetSBCSBuffer might have used a different memory allocator or returned a pointer to a location internal to sFilePath. In the last case it would be very bad to call any deallocator.

I just noticed you answered the question yourself in your comment to elder_george's answer. The implementation used new[] so you need to delete[].

J. Loomis
int len = WideCharToMultiByte(CP_ACP, 0, str, -1, 0, 0, 0, 0); // allocate the buffer to hold the converted string LPSTR result = new char[len]; // do the conversion WideCharToMultiByte(CP_ACP, 0, str, -1, result, len, 0, 0); return result;This is what is written in getsbcsbuffer.
ckv
Sorry I put the answer in the original text because I don't know how to hyperlink in a comment (new at this). You just posted that result is allocated using new char[len] so you must free it by using delete[] szFileName. Always match new with delete and new[] with delete[].
J. Loomis
thanks i followed the same
ckv