Microsoft KB Archive/250321

= BUG: The CString::Delete Function Does Not Return the Correct Value =

Article ID: 250321

Article Last Modified on 11/21/2006

-

APPLIES TO

 Microsoft Foundation Class Library 4.2, when used with:  Microsoft Visual C++ 6.0 Enterprise Edition

 Microsoft Visual C++ 6.0 Professional Edition

 Microsoft Visual C++ 6.0 Standard Edition 

-

<div class="notice_section">

This article was previously published under Q250321

<div class="symptoms_section">

SYMPTOMS
The CString::Delete function returns the length of the original string instead of the length of the modified string.

<div class="cause_section">

CAUSE
The CString::Delete function initializes a local variable (nNewLength) with the length of the original string and does not change this variable to reflect the length of the changed string.

Here is the source code for the Delete method of the CString class (reproduced from the Strex.cpp file, which is located in the Mfc/Src folder): int CString::Delete(int nIndex, int nCount /* = 1 */) {   if (nIndex < 0) nIndex = 0; int nNewLength = GetData->nDataLength; if (nCount > 0 && nIndex < nNewLength) {       CopyBeforeWrite; int nBytesToCopy = nNewLength - (nIndex + nCount) + 1;

memcpy(m_pchData + nIndex,           m_pchData + nIndex + nCount, nBytesToCopy * sizeof(TCHAR)); GetData->nDataLength = nNewLength - nCount; }

return nNewLength; }

<div class="resolution_section">

RESOLUTION
To work around this problem, call the GetLength method on the modified CString class to get its length: CString str2 = "Hockey is best!"; str2.Delete(6, 3); int n = str2.GetLength;

<div class="status_section">

STATUS
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

<div class="moreinformation_section">

Steps to Reproduce Behavior
<ol> Create a dialog box-based application by using MFC AppWizard.</li>  Place a button on the dialog box and create a handler for it. Copy the following code to the button's handler:

//The following example demonstrates the use of CString::Delete: CString str2 = "Hockey is best!"; TRACE("Length of the original string: %d\n", str2.GetLength); int n = str2.Delete(6, 3); TRACE("Actual length of the modified string: %d\n", str2.GetLength); TRACE("Return value from Delete method: %d\n",n); </li> Compile and run the application under the Visual C++ debugger by pressing F5. Click the button.</li></ol>

You should see in the output window that the return value from the Delete method is the length of the original string, not the length of modified string.

Additional query words: CString delete length return

Keywords: kbbug kbpending kbstring KB250321

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.