-
June 25th, 1999, 10:29 AM
#1
Dynamic char* Allocation
What is wrong with the following code? The code crashes on the delete statment (true condition) every time I run the code. Thanks.
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(strOut + "\n");
// Write value
fileOut->WriteString(pch);
fileOut->WriteString("\n");
delete [] pch;
return true;
}
else
{
delete [] pch;
return false;
}
}
-Albert
-
June 25th, 1999, 10:40 AM
#2
Re: Dynamic char* Allocation
You are writing out of bounds:
UINT nBytesRead;
char *pch = new char[nLength];
pch[nLength] = NULL; <<--Out of bounds!!
First, arrays are 0-based, therefoer pch[nLength] is over the limit by 1. Also, the value that should be written is '\0', not NULL. I'm sure you got a warning on the type mismatch.
Here is the corrected code (at least for the first part)
bool ReadWriteString(CFile* fileIn, CStdioFile* fileOut, CString strOut, unsigned short nLength)
{
UINT nBytesRead;
char *pch = new char[nLength + 1];
pch[nLength] = '\0';
nBytesRead = fileIn->Read(pch, nLength);
...
Regards,
Paul McKenzie
-
June 25th, 1999, 10:56 AM
#3
Re: Dynamic char* Allocation
correct about the out-of-bounds thing, but it really doesn't matter if he assigns NULL or '\0' or 0 to pch[nLength] , they all have the same value of 0x00, which is what the NULL Byte is.
Strousstrup, that guy that created c++, tells us that "A constant expression that evaluates to 0 is converted to a pointer, commonly called the NULL pointer".
--michael
-
June 25th, 1999, 11:04 AM
#4
Re: Dynamic char* Allocation
Thanks for the help. I noticed in the code sample you posted that you delimited '\0' with the single-quote character. What is the reason for this? Is there any difference between using double and single quotes?
-Albert
-
June 25th, 1999, 11:10 AM
#5
Re: Dynamic char* Allocation
the '\0' one byte (or two if you are using double-byte characters) that represents NULL.
"\0" is a string (2 chars or 4 if you are using double-byte chars), so assigning it to a char would give an error that it cannot convert form a char[2] to a char.
--michael
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|