Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CString to char*

We are using the CString class throughout most of our code. However sometimes we need to convert to a char *. at the moment we have been doing this using variable.GetBuffer(0) and this seems to work ( this mainly happens when passing the Csting into a function where the function requires a char *). The function accepts this and we keep going.

However we have lately become worried about how this works, and whether there is a better way to do it.

The way i understand it to work is it passes a char pointer into the function that points at the first character in the CString and all works well.

I Guess we are just worried about memory leaks or any unforseen circumstances where this might not be a good idea.

like image 353
Mark Lakewood Avatar asked Feb 18 '09 01:02

Mark Lakewood


People also ask

How do I copy a CString to a char array?

This can be done with the help of c_str() and strcpy() function of library cstring. The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.

How do you find the length of a CString?

To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in a CString object.

What is the difference between char and const char?

Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.


1 Answers

If your functions only require reading the string and not modifying it, change them to accept const char * instead of char *. The CString will automatically convert for you, this is how most of the MFC functions work and it's really handy. (Actually MFC uses LPCTSTR, which is a synonym for const TCHAR * - works for both MBC and Unicode builds).

If you need to modify the string, GetBuffer(0) is very dangerous - it won't necessarily allocate enough memory for the resulting string, and you could get some buffer overrun errors.

As has been mentioned by others, you need to use ReleaseBuffer after GetBuffer. You don't need to do that for the conversion to const char *.

like image 192
Mark Ransom Avatar answered Oct 18 '22 09:10

Mark Ransom