Avatar of KaranGupta
KaranGupta asked on

dispose TChar*

Hi

I am declaring a variable

const TCHAR* tes;

after using it I want to free the memory.

How can I do that.

Regards
Karan
Editors IDEsVisual C++.NETC++

Avatar of undefined
Last Comment
KaranGupta

8/22/2022 - Mon
alb66

If you didn't allocate memory dinamically (with new) you don't need to free it.
itsmeandnobodyelse

>>>> after using it I want to free the memory.

The allocation of the pointer variable itself (4 bytes or 8 bytes depending on compiler)  will be allocated at the stack and doesn't need to get freed. The storage automatically was freed when the variable goes out of scope (after the ending } of the current block).

>>>> If you didn't allocate memory dinamically (with new) you don't need to free it.

To add to above information:

if you assigned a pointer value to the variable where you did *not* made a new before, you may *not* call delete or the program will crash.

(A)
// assign a literal
const TCHAR* tes = _T("Hello World");

...
delete []tes;  // error, will crash


(B)
{
   const TCHAR* tes =NULL;
   CString  s = "Hello World";

   tes = (LPCTSTR) s;

   delete []tes;   // if it compiles it won't crash here ....
}
// ... but here, when the  CString  s goes out of scope and the buffer was deleted once more

(C)
   const TCHAR* tes = new TCHAR[32];
   tcscpy((LPTSTR)tes, _T("Hello World"));
   ...
   delete []tes;  // ok


Note, the cast to LPTSTR was necessary because tes was defined as const.




ASKER
KaranGupta

(A)
// assign a literal
const TCHAR* tes = _T("Hello World");

...
delete []tes;  // error, will crash

This is my case

If I don't free the memory space explicitly then it will do it automatically

that is what you are saying.

Regards
Karan
Your help has saved me hundreds of hours of internet surfing.
fblack61
alb66

The line

const TCHAR* tes = _T("Hello World");

doesn't allocate any memory so you have not to free it (neither you nor the system).
ASKER CERTIFIED SOLUTION
itsmeandnobodyelse

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
KaranGupta

Thanks a lot