From: Guido van Rossum Date: Mon, 23 Sep 2002 20:46:52 +0000 (+0000) Subject: Backport 2.166 from trunk: X-Git-Tag: v2.2.2b1~153 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=1c4a45761c6654e5877ca767b607cf4e5b3c0e2c;p=thirdparty%2FPython%2Fcpython.git Backport 2.166 from trunk: Fix SF bug 599128, submitted by Inyeol Lee: .replace() would do the 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. --- diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index d4e247196dfb..b1ba48dd3735 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -3509,10 +3509,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));