Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

new & delete operators - causing memory check error

Status
Not open for further replies.

mattKnight

Programmer
May 10, 2002
6,222
0
36
GB
Code:
// mpszUser is a private class member of type LPCTSTR
void CXMLInfo::put_User(BSTR szUser)
{
	_bstr_t bstrTemp(szUser);

	mpszUser = new TCHAR[bstrTemp.length()];

	_stprintf(const_cast<LPTSTR>(mpszUser), _T("%s"),(LPCTSTR)bstrTemp);

}

The above code is part of a class I am using to store information (extracted from an XML file as it happens).

When I am finished using the class, I need to free the memory used by the TCHAR array so I use the following in the destructor

Code:
	if(mpszUser != NULL)
   	delete  const_cast<LPTSTR>(mpszUser);
[code]

However, whenever this gets called my debug screen shows
[quote]
memory check error at 0x009726D6 = 0x00, should be 0xFD.
[/quote]

Can anyone tell me why?  I have tried using the array version of delete (i.e. delete []) which I understand is what i should be using, but there is now difference.

Take Care

Matt
If at first you don't succeed, skydiving is not for you.
 
You need to add one more byte to the amount of memory you allocate for mpszUser, to reserve space for the terminating NULL character:

Code:
mpszUser = new TCHAR[bstrTemp.length()+1];

Also, you can change the "%s" to "%S" and remove the type-cast of bstrTemp to LPCTSTR.

Also, you shouldn't need to do any of that type casting, especially the "const_cast".
 
Arrg - NULL terminator again....

You'd have thought I might have learnt by now!

Thank you

However, I am interested why you say I don't need the const_cast of mpszUser.

If I remove it, the compiler gives a "can't convert from const char * to char *"

As a separate, but related question, if I initialise a variable thus

Code:
LPCTSTR pszTest = _T("I am a test\0");
[\code]

How does the _T() macro allocate the memory?  Do I need to delete pszTest?  or is that handled in some other way? 


Take Care

Matt
If at first you don't succeed, skydiving is not for you.
 
Code:
LPCTSTR pszTest = _T("I am a test\0");

How does the _T() macro allocate the memory? Do I need to delete pszTest? or is that handled in some other way?

String litterals are allocated during compilation, placed as data segments together with program code in .exe file and don't need to be freed.
 
One more note - "I am a test" already means a null-terminated string and explicit extra \0 character at the end ("I am a test\0") is not necessary.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top