diff --git a/Lib/multiprocessing/shared_memory.py b/Lib/multiprocessing/shared_memory.py index de74a0cbbba853..93184c0dbd8b3b 100644 --- a/Lib/multiprocessing/shared_memory.py +++ b/Lib/multiprocessing/shared_memory.py @@ -322,7 +322,13 @@ def __init__(self, sequence=None, *, name=None): self._types_mapping[type(item)] if not isinstance(item, (str, bytes)) else self._types_mapping[type(item)] % ( - self._alignment * ((len(self._encode_value(item)) - 1) // self._alignment + 1), + # An empty str/bytes still needs one alignment unit of + # storage: a zero-length slot would overlap the next + # item (or the metadata area), and __setitem__() could + # then silently overwrite it with a fixed-size value. + max(self._alignment, + self._alignment * ((len(self._encode_value(item)) - 1) + // self._alignment + 1)), ) for item in sequence ] diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 540189147cb4d7..19c6b2b3b97d2e 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -5254,6 +5254,27 @@ def test_shared_memory_ShareableList_basics(self): finally: empty_sl.shm.unlink() + def test_shared_memory_ShareableList_empty_items(self): + # An empty str or bytes still needs a slot of its own: a zero-length + # slot overlaps the next item (or the metadata area), so storing a + # fixed-size value into it used to overwrite the following item, or + # to corrupt the packing formats and raise struct.error. + sl = shared_memory.ShareableList(['', b'', 42]) + self.addCleanup(sl.shm.unlink) + try: + self.assertEqual(sl.format, '8s8sq') + self.assertEqual(list(sl), ['', b'', 42]) + sl[0] = 7 + sl[1] = 8 + self.assertEqual(list(sl), [7, 8, 42]) + sl[2] = '' + self.assertEqual(list(sl), [7, 8, '']) + # A trailing empty item must not run into the metadata area. + sl[2] = 3 + self.assertEqual(list(sl), [7, 8, 3]) + finally: + sl.shm.close() + def test_shared_memory_ShareableList_unpackable_value(self): # Values of a supported type that cannot be packed must not leave # the newly created shared memory block behind. diff --git a/Misc/NEWS.d/next/Library/2026-12-03-02-41-21.gh-issue-163051.APE7KX.rst b/Misc/NEWS.d/next/Library/2026-12-03-02-41-21.gh-issue-163051.APE7KX.rst new file mode 100644 index 00000000000000..30d69549827bae --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-03-02-41-21.gh-issue-163051.APE7KX.rst @@ -0,0 +1,2 @@ +Fix a zero-length slot for an empty :class:`str` or :class:`bytes` in +:class:`multiprocessing.shared_memory.ShareableList`.