awd
asked on
Dynamic char* Allocation
What is wrong with the following code? It crashes on the delete statement (true condition) every time I run it.
bool ReadWriteString(CFile* fileIn, CStdioFile* fileOut, CString strOut, unsigned short nLength)
{
UINT nBytesRead;
char *pch = new char[nLength];
pch[nLength] = NULL;
nBytesRead = fileIn->Read(pch, nLength);
if (nBytesRead == nLength)
{
// Write Label
fileOut->WriteString(strOu t + "\n");
// Write value
fileOut->WriteString(pch);
fileOut->WriteString("\n") ;
delete [] pch;
return true;
}
else
{
delete [] pch;
return false;
}
}
bool ReadWriteString(CFile* fileIn, CStdioFile* fileOut, CString strOut, unsigned short nLength)
{
UINT nBytesRead;
char *pch = new char[nLength];
pch[nLength] = NULL;
nBytesRead = fileIn->Read(pch, nLength);
if (nBytesRead == nLength)
{
// Write Label
fileOut->WriteString(strOu
// Write value
fileOut->WriteString(pch);
fileOut->WriteString("\n")
delete [] pch;
return true;
}
else
{
delete [] pch;
return false;
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Except the code doesn't try to write past the end of the allocated array. The
fileOut->WriteString(pch)
might die because the string might not be terminated (can't tell this from the shown code.) However there is no reason why the delete [] would die.
fileOut->WriteString(pch)
might die because the string might not be terminated (can't tell this from the shown code.) However there is no reason why the delete [] would die.
ASKER
mandhjo was correct. Although I think he made a careless mistake. The line:
pch[nLength + 1] = NULL should read
pch[nLength] = NULL after making the suggested change.
Thanks for the comments everyone.
pch[nLength + 1] = NULL should read
pch[nLength] = NULL after making the suggested change.
Thanks for the comments everyone.
As I mentioned later in my answer, I believe the correct way to initialize any buffer is to initialize ALL of it to NULL, not just what you THINK to be the last character.
Thanks for the points, glad I could help.
Thanks for the points, glad I could help.
allocates nLength characters, usable from
pch[0]
to
pch[nLength - 1]
so
pch[nLength] = 0;
will write in un allocated memory