This method retrieves a pointer to the internal character buffer for the CString object. The returned LPTSTR is not const and thus allows direct modification of CString contents.

If nMinBufLength is greater than the length of the current buffer, the call to GetBuffer will destroy the current buffer. Replace it with a buffer of the requested size, and reset the reference count to zero. If you have previously called LockBuffer on this buffer, you will lose the lock on the buffer.

LPTSTR GetBuffer(
int nMinBufLength ); 


  • nMinBufLength
    Specifies the minimum size of the character buffer in characters. This value does not include space for a null terminator.

Return Value

This is an LPTSTR pointer to the character buffer of the null-terminated object.


If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString methods.

The address returned by GetBuffer may not be valid after the call to ReleaseBuffer since additional CString operations may cause the CString buffer to be reallocated. The buffer will not be reallocated if you do not change the length of the CString.

The buffer memory will be freed automatically when the CString object is destroyed.

Note that, if you keep track of the string length yourself, you should not append the terminating null character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating null character, you should pass –1 for the length to ReleaseBuffer, which will perform a on the buffer to determine its length.


The following example demonstrates the use of CString::GetBuffer.

// example for CString::GetBuffer
CString s( "abcd" );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
LPTSTR p = s.GetBuffer( 10 );
lstrcpy( p, _T("Hello") );  // directly access CString buffer
s.ReleaseBuffer( );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";


  Windows CE versions: 1.0 and later
  Header file: Declared in Afx.h
  Platform: H/PC Pro, Palm-size PC, Pocket PC

See Also

CString::GetBufferSetLength, CString::ReleaseBuffer