How do I release the memory of a LPWSTR?

           LPWSTR pszAuxClass[]={L"top",L"symark-UserContext"};

Thank you.
lapuccaAsked:
Who is Participating?
 
jkrCommented:
Not at all - these are constant string literals in an array, the compiler will take care of the cleanup. Udually, they're even placed in a 'const' data segment, so you even can't do that.
0
 
MysidiaCommented:
With that declaration, you don't.

You can only release memory explicitly during runtime that you actually allocated during runtime, such
as with the new operator.

In case you use the new operator,  there is a corresponding  delete  operator to release.

Automatic variables are released when their lifetime ends,  I.E.  if they're defined inside a block, when
the block exits, or the function returns,  or if they're global: when the program exits.

But string literals like   "symark-UserContext"     are global.
0
 
AxterCommented:
>>LPWSTR pszAuxClass[]={L"top",L"symark-UserContext"};

I recommend that you use a constant pointer when ever you declare a pointer to a string literal.
Example:
LPCWSTR pszAuxClass[]={L"top",L"symark-UserContext"};

This will prevent you from accidently trying to modify a string literal.
0
 
itsmeandnobodyelseCommented:
>>>> How do I release the memory of a LPWSTR

if you would have

  LPWSTR lpwsz = new WCHAR[20];
  wcscpy(lpwsz, L"ABCDEFGHI");

  ...

you would need to release by

  delete [] lpwsz;
 
after use.

If you have

 LPWSTR* lpwszArr = new LPWSTR[10];
 for (int i = 0; i < sizeof(lpwszArr)/sizeof(LPWSTR); ++i)
 {
       LPCWSTR prefix = L"file";
     
       wcscpy(lpwszArr[i], prefix);
       WCHAR wc = L'0' + (WCHAR)i;
       wcsncat( lpwszArr[i], &wc, 1);
  }
         
you would release allocation by
 
   for (i = 0; i < sizeof(lpwszArr)/sizeof(LPWSTR); ++i)
   {
        delete[] lpwszArr[i];
    }
    delete[] lpwszArr;

Generally, you have to delete if - and only if - you have made a new before.

Regards, Alex

0
 
itsmeandnobodyelseCommented:
correction:

LPWSTR* lpwszArr = new LPWSTR[10];
 for (int i = 0; i < 10; ++i)  
 {
       LPCWSTR prefix = L"file";
       lpwszArr[i] = new WCHAR[sizeof("file")+2];
       wcscpy(lpwszArr[i], prefix);
       WCHAR wc = L'0' + (WCHAR)i;
       wcsncat( lpwszArr[i], &wc, 1);
  }
         
you would release allocation by
 
   for (i = 0; i < 10; ++i)
   {
        delete[] lpwszArr[i];
    }
    delete[] lpwszArr;


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.