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(
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 *
.
@ the OP: >>> I Guess we are just worried about memory leaks or any ...
Hi, calling the GetBuffer method won't lead to any memory leaks. Because the destructor is going to deallocate the buffer anyway. However, others have already warned you about the potential issues with calling this method.
@Can >>> when you call the getbuffer function it allocates memory for you.
This statement is not completely true. GetBuffer(0) does NOT allocate any memory. It merely returns a pointer to the internal string buffer that can be used to manipulate the string directly from "outside" the CString class.
However, if you pass a number, say N to it like GetBuffer(N), and if N is larger than the current length of the buffer, then the function ensures that the returned buffer is at least as large as N by allocating more memory.
Cheers, Rajesh. MVP, Visual ++.
when you call the getbuffer function it allocates memory for you. when you have done with it, you need to call releasebuffer to deallocate it
try the documentation at http://msdn.microsoft.com/en-us/library/awkwbzyc.aspx for help on that.