]> granicus.if.org Git - python/commitdiff
Fix SF bug 599128, submitted by Inyeol Lee: .replace() would do the
authorGuido van Rossum <guido@python.org>
Fri, 23 Aug 2002 18:50:21 +0000 (18:50 +0000)
committerGuido van Rossum <guido@python.org>
Fri, 23 Aug 2002 18:50:21 +0000 (18:50 +0000)
wrong thing for a unicode subclass when there were zero string
replacements.  The example given in the SF bug report was only one way
to trigger this; replacing a string of length >= 2 that's not found is
another.  The code would actually write outside allocated memory if
replacement string was longer than the search string.

(I wonder how many more of these are lurking?  The unicode code base
is full of wonders.)

Bugfix candidate; this same bug is present in 2.2.1.

Lib/test/test_unicode.py
Objects/unicodeobject.c

index 90147eb5feea906b4716bd2024ce2b62b1529919..9e36316d79f5ddcd15429e6fde32950e80021f85 100644 (file)
@@ -213,6 +213,8 @@ test('replace', u'one!two!three!', u'one!two!three!', u'x', u'@', 2)
 test('replace', u'abc', u'-a-b-c-', u'', u'-')
 test('replace', u'abc', u'-a-b-c', u'', u'-', 3)
 test('replace', u'abc', u'abc', u'', u'-', 0)
+test('replace', u'abc', u'abc', u'ab', u'--', 0)
+test('replace', u'abc', u'abc', u'xy', u'--')
 test('replace', u'', u'', u'', u'')
 
 test('startswith', u'hello', True, u'he')
index 6dea94f4798f93c4019b61e2c22a22dfd7dac664..920f9ea2d86449b468dde94e567d59be683261dd 100644 (file)
@@ -3534,10 +3534,16 @@ PyObject *replace(PyUnicodeObject *self,
         n = count(self, 0, self->length, str1);
         if (n > maxcount)
             n = maxcount;
-        if (n == 0 && PyUnicode_CheckExact(self)) {
+        if (n == 0) {
             /* nothing to replace, return original string */
-            Py_INCREF(self);
-            u = self;
+            if (PyUnicode_CheckExact(self)) {
+                Py_INCREF(self);
+                u = self;
+            }
+            else {
+                u = (PyUnicodeObject *)
+                    PyUnicode_FromUnicode(self->str, self->length);
+           }
         } else {
             u = _PyUnicode_New(
                 self->length + n * (str2->length - str1->length));