Index: src/libchcore/TString.cpp =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -rbe86ea000c8ee746379fd5018c9f43a9b1cddfa1 --- src/libchcore/TString.cpp (.../TString.cpp) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/TString.cpp (.../TString.cpp) (revision be86ea000c8ee746379fd5018c9f43a9b1cddfa1) @@ -668,6 +668,8 @@ size_t stWhatLen = _tcslen(pszWhat); size_t stWithWhatLen = _tcslen(pszWithWhat); + size_t stNewLen = stCurrentLength; + // resize internal string if needed if(stWithWhatLen > stWhatLen) { @@ -681,14 +683,22 @@ } if(stSizeDiff > 0) - EnsureWritable(stCurrentLength + stSizeDiff + 1); + stNewLen = stCurrentLength + stSizeDiff + 1; } + bool bMadeWritable = false; + // replace size_t stStartPos = 0; size_t stFindPos = 0; while((stFindPos = Find(pszWhat, stStartPos)) != std::numeric_limits::max()) { + if(!bMadeWritable) + { + EnsureWritable(stNewLen); + bMadeWritable = true; + } + // Sample string "ABCdddb" (len:6), searching for "dd" (len 2) to replace with "x" (len 1) // found string pos is: [stFindPos, stFindPos + stWhatLen) -- sample ref: [3, 3 + 2) // we need to Index: src/libchcore/Tests/TestsTString.cpp =================================================================== diff -u -N -r9479911a096555a7504c5c8a8eaee83ecb63440c -rbe86ea000c8ee746379fd5018c9f43a9b1cddfa1 --- src/libchcore/Tests/TestsTString.cpp (.../TestsTString.cpp) (revision 9479911a096555a7504c5c8a8eaee83ecb63440c) +++ src/libchcore/Tests/TestsTString.cpp (.../TestsTString.cpp) (revision be86ea000c8ee746379fd5018c9f43a9b1cddfa1) @@ -615,3 +615,13 @@ strValue.TrimRightSelf(L"gn"); EXPECT_EQ(strValue, L"Some stri"); } + +TEST(TStringTests, ReplaceAffectingOtherStringInstancesBug) +{ + TString strValue(_T("Some string")); + TString strSecond(strValue); + + strValue.Replace(_T("Some "), _T("No ")); + + EXPECT_EQ(strSecond, _T("Some string")); +}