0

Hi, I'm looking for a function that will convert CString to char*, I found the function

char* ConvertToChar(const CString &s)
{
 int nSize = s.GetLength();
 char *pAnsiString = new char[nSize+1];
 memset(pAnsiString,0,nSize+1);
 wcstombs(pAnsiString, s, nSize+1);
 return pAnsiString;
}

The problem is you cann see that there is the use of new operator in the line:

char *pAnsiString = new char[nSize+1];

This can cause memory leak in the future, also in C++ after using new we must use delete, the problem is if I use delete in the function the function returns NULL.
Ideas?
Thanks

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

The function that callers ConvertToChar() must delete the memory when done with it. That's a common requirement of programming. Of course you could also return std::string instead of char* which would eliminate the need for allocation -- but if this is for eVC++ compiler you won't have that option. A third option is to make the calling function pass in a pointer to the buffer.

char* ConvertToChar(const CString &s, char* pAnsiString, int bufsize)
{
 wcstombs(pAnsiString,(LPCTSTR) s, bufsize);
 return pAnsiString;
}

Also, you might as well delete that memset line, no point wasting cpu cycles clearing memory and immediately copying something else into that same memory.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.