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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.