PRB: STL string Class insert Function Does Not Work as Expected (168376)



The information in this article applies to:

  • The Standard C++ Library, when used with:
    • Microsoft Visual C++, 32-bit Enterprise Edition 4.2
    • Microsoft Visual C++, 32-bit Professional Edition 4.2
    • Microsoft Visual C++, 32-bit Enterprise Edition 5.0
    • Microsoft Visual C++, 32-bit Professional Edition 5.0
    • Microsoft Visual C++, 32-bit Enterprise Edition 6.0
    • Microsoft Visual C++, 32-bit Professional Edition 6.0
    • Microsoft Visual C++, 32-bit Learning Edition 6.0

This article was previously published under Q168376

SYMPTOMS

The string::insert member function does not work as expected. This is because the same string object is used for modification and input. Many data manipulation routines do not check for overlapping or identical arguments, causing unexpected results.

RESOLUTION

Create a temporary copy of the string as shown below:
s.insert(0, string("b"), 1);
				

STATUS

This behavior is by design.

MORE INFORMATION

Steps to Reproduce Behavior

#include <iostream>
#include <string>
using namespace std ;

void f1()
 {
  string s ("abc");
  s.insert (0, s, 1, 1);
  cout << "s (should be 'babc'): " << s << endl << endl;
 }

int main ()
  {
    f1();// prints "aabc" instead of "babc"
    return 0 ;
  }
				

Modification Type:MajorLast Reviewed:12/2/2003
Keywords:kbprb kbprogramming KB168376