Convert CString to char*
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
dev.cplusplus
Junior Poster in Training
61 posts since Jun 2006
Reputation Points: 10
Solved Threads: 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.
Ancient Dragon
Retired & Loving It
30,050 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343