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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why CString gets longer as the source char*? 1

Status
Not open for further replies.

firelex

Programmer
Jan 10, 2002
118
DE
Hi, all!
The problem is:
I have a function:
Code:
BOOL CMyClass::ReadFile(CString *path, CString *data)
{
 CFile file;
 if (!file.Open(*path, CFile::modeRead)) {
  return FALSE;
 } else {
  try {
   char *buf;
   buf = (char*) calloc(file.GetLength(), sizeof(char));

   ZeroMemory(buf,sizeof(buf));
   file.Read(buf, file.GetLength());
   CString temp="";
   temp = buf;
   TRACE("temp <%i> VS file <%i>", temp.GetLength(), file.GetLength());
   *data = buf;
   free(buf);
  } catch (CFileException e) {
   return FALSE;
  }
  file.Close();
  return TRUE;
}

Why do variable [tt]temp[/tt] has another length as the [tt]file.GetLength()[/tt] gives back? (one can see it in the TRACE output). In my case it was "temp <1560> VS file <1537>" [sadeyes]
 
2 things:

Code:
buf = (char*) calloc(file.GetLength(), sizeof(char));
ZeroMemory(buf,sizeof(buf));

a) you need to call, file.GetLength() + 1. To make space for the NULL character at the end.
b) There is no need to call ZeroMemory because calloc does that for you. If you used malloc instead then you would need to make that call.

The reason for the bigger size is that it doesnt know where the text ends because you havent included enough space for a NULL terminator (see point (a))


Skute

&quot;There are 10 types of people in this World, those that understand binary, and those that don't!&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top