I was trying to build a class that deal with String operators. However, for no convincing reason, it sometime crashed during delete[] operator. I used strsafe library to do all internal string operation.
//qstring
LPTSTR m_string;
void QString::operator +=(const QString &_in) //Concat m_string with _in.m_string
{
size_t size = strlength(m_string) + strlength(_in.m_string) +1; //new size
LPTSTR buffer = new TCHAR[size]; //alloc buffer
::StringCchCopy(buffer,strlength(m_string)+1,m_string); //copy current m_string to buffer
::StringCchCat(buffer, size, _in.m_string); //concat buffer with the input
Replace(buffer); //replace this object with m_string
delete[] buffer; //dealloc
}
void QString::Replace(LPCTSTR src) //replace m_string with src
{
size_t size = strlength(src)+1; //new size
Alloc(size);
::StringCchCopy(m_string,size,src); //copy src to m_string
}
void QString::Alloc(size_t size) //Dynamic allocation
{
if(m_string != NULL) Free();
m_string = new TCHAR[size+1];
}
void QString::Free() //Free m_string
{
delete[] m_string; //Sometime crashes here
m_string = NULL;
}
QString ToStr(int _in) //Convert Integer to qstring
{
int size = 1;
int f = _in;
while(f > 0)
{
f /=10;
size++;
}
TCHAR* buf = new TCHAR[size];
for(int i = 0; i < size; i++) buf[i] = (TCHAR)TEXT("");
QString result(L"undef");
if(::_itow_s(_in,buf,size,10) == 0) //No error code = ok
{
result = buf;
}
delete[] buf;
return result;
}
//Example 1: Does not crashed
int ::WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd)
{
QString a(L"");
a += L"TEST";
a += ToStr(1000);
::MessageBox(0,a.GetStr(),L"NOTHING",MB_OK);
return 0;
}
//Example 2: Print weird characters plus some of the current characters (Unicode problems?)
int ::WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd)
{
QString a(L"");
a += L"TESTTESTESTEST";
a += ToStr(1000);
::MessageBox(0,a.GetStr(),L"NOTHING",MB_OK);
return 0;
}
//Example 3: Crashes on load
int ::WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd)
{
QString a(L"");
a += L"TESTTESTESTEST";
a += ToStr(1000);
a += L"TESTESTEST";
a += ToStr(100);
::MessageBox(0,a.GetStr(),L"NOTHING",MB_OK);
return 0;
}
It crashed on delete[] operator in Free(). With error of either
HEAP[StringTest.exe]: Invalid Address specified to RtlFreeHeap( 003C0000, 003C46A8 )
or
HEAP[StringTest.exe]: Heap block at 003C4750 modified at 003C475C past requested size of 4