[ACCEPTED]-CString to char*-cstring

Accepted answer
Score: 24

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

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

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

Score: 8

@ the OP: >>> I Guess we are just worried about memory leaks or any ...

Hi, calling the GetBuffer method 16 won't lead to any memory leaks. Because 15 the destructor is going to deallocate the 14 buffer anyway. However, others have already 13 warned you about the potential issues with 12 calling this method.

@Can >>> when you call the getbuffer function it allocates memory for you.

This statement 11 is not completely true. GetBuffer(0) does 10 NOT allocate any memory. It merely returns 9 a pointer to the internal string buffer 8 that can be used to manipulate the string 7 directly from "outside" the CString class.

However, if 6 you pass a number, say N to it like GetBuffer(N), and 5 if N is larger than the current length of 4 the buffer, then the function ensures that 3 the returned buffer is at least as large 2 as N by allocating more memory.

Cheers, Rajesh. MVP, Visual 1 ++.

Score: 3

when you call the getbuffer function it 3 allocates memory for you. when you have 2 done with it, you need to call releasebuffer 1 to deallocate it

Score: 1

try the documentation at http://msdn.microsoft.com/en-us/library/awkwbzyc.aspx for help on that.


More Related questions