Microsoft KB Archive/250321

From BetaArchive Wiki
< Microsoft KB Archive
Revision as of 13:51, 21 July 2020 by X010 (talk | contribs) (Text replacement - """ to """)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Article ID: 250321

Article Last Modified on 11/21/2006


  • 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

This article was previously published under Q250321


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


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)
        int nBytesToCopy = nNewLength - (nIndex + nCount) + 1;

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

    return nNewLength;


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();


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


Steps to Reproduce Behavior

  1. Create a dialog box-based application by using MFC AppWizard.
  2. 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);   
  3. Compile and run the application under the Visual C++ debugger by pressing F5. Click the button.

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