I have a member variable
wchar_t * _message;
This array is allocated in the constructor,
_message = new wchar_t [messageLength];
But when I try to free the memory with delete in by destructor, it crashes with a a HEAP CORRUPTION error.
This my class:
class ExampleZero
{
public:
ExampleZero( wchar_t* cppMessage);
~ExampleZero(void);
private:
const wchar_t *_message;
};
ExampleZero::ExampleZero( wchar_t* cppMessage)
{
_message = NULL;
errno_t winError;
if (cppMessage == NULL){
fwprintf(stderr, L"Null pointer for string.\n");
return;
}
size_t messageLength = wcslen(cppMessage);
if (messageLength < 1){
fwprintf(stderr, L"string is empty or invalid.\n");
return;
}
try{
long address=NULL;
_message = new wchar_t [messageLength];
address = (long) _message;
fprintf(stderr,"%x",address);
}
catch(std::exception& e){
fprintf(stderr, e.what());
return;
}
if(_message == NULL){
return;
}
SecureZeroMemory((PVOID)_message,messageLength);
winError = wcscpy_s((wchar_t *)_message, messageLength+1, cppMessage);
}
ExampleZero::~ExampleZero(void)
{
if(_message != NULL){
try{
/* Why does it crash here? */
delete [] _message;
}
catch(std::exception& e){
fprintf(stderr, e.what());
}
_message=NULL;
}
}
/*******************/
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
ExampleZero * example0;
example0 = new ExampleZero(L"I Live");
delete example0;
}
return nRetCode;
}