Issue #16215: Fix potential double memory free in str.replace().
Patch by Serhiy Storchaka.
diff --git a/Misc/NEWS b/Misc/NEWS
index aa9f6c7..df8f014 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@
 Core and Builtins
 -----------------
 
+- Issue #16215: Fix potential double memory free in str.replace().  Patch
+  by Serhiy Storchaka.
+
 - Issue #16290: A float return value from the __complex__ special method is no
   longer accepted in the complex() constructor.
 
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index 7856e77..dd8d7b2 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -9959,6 +9959,7 @@
                 /* widen self and buf1 */
                 rkind = kind2;
                 if (release1) PyMem_Free(buf1);
+                release1 = 0;
                 sbuf = _PyUnicode_AsKind(self, rkind);
                 if (!sbuf) goto error;
                 srelease = 1;
@@ -10020,6 +10021,7 @@
             if (!sbuf) goto error;
             srelease = 1;
             if (release1) PyMem_Free(buf1);
+            release1 = 0;
             buf1 = _PyUnicode_AsKind(str1, rkind);
             if (!buf1) goto error;
             release1 = 1;