diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index 67960f5709b08e..332c6456026546 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -2414,6 +2414,30 @@ def __index__(self): self.assertEqual(instance.ba[0], ord("?"), "Assigned bytearray not altered") self.assertEqual(instance.new_ba, bytearray(0x180), "Wrong object altered") + def check_strip_mutate(self, method, initial, expected): + ba = bytearray(initial) + + class S: + def __buffer__(self, flags): + return memoryview(b" ") + + def __release_buffer__(self, view): + ba.clear() + + meth = getattr(ba, method) + result = meth(S()) + self.assertEqual(result, bytearray(expected)) + self.assertEqual(ba, bytearray(b'')) + + def test_strip_mutate(self): + self.check_strip_mutate('strip', b' abc ', b'abc') + + def test_lstrip_mutate(self): + self.check_strip_mutate('lstrip', b' abc ', b'abc ') + + def test_rstrip_mutate(self): + self.check_strip_mutate('rstrip', b' abc ', b' abc') + def test_search_methods_reentrancy_raises_buffererror(self): # gh-142560: Raise BufferError if buffer mutates during search arg conversion. class Evil: diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-09-21-26-31.gh-issue-161688.NAn55a.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-09-21-26-31.gh-issue-161688.NAn55a.rst new file mode 100644 index 00000000000000..fe653e0ee3b85b --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-09-21-26-31.gh-issue-161688.NAn55a.rst @@ -0,0 +1 @@ +Fix :func: bytearray.strip from performing segmentation violation diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c index 317534c99f038d..0cfaadbfcde93e 100644 --- a/Objects/bytearrayobject.c +++ b/Objects/bytearrayobject.c @@ -2468,9 +2468,13 @@ bytearray_strip_impl_helper(PyByteArrayObject* self, PyObject* bytes, int stript } while (right >= left && memchr(bytesptr, (unsigned char)myptr[right], byteslen)); right++; } + + + PyObject *res = PyByteArray_FromStringAndSize(myptr + left, right - left); + if (bytes != Py_None) PyBuffer_Release(&vbytes); - return PyByteArray_FromStringAndSize(myptr + left, right - left); + return res; } /*[clinic input]