[New-bugs-announce] [issue41673] Result of multiprocessing.heap.BufferWrapper.create_memoryview can point to freed memory

Eric Wieser report at bugs.python.org
Mon Aug 31 08:56:22 EDT 2020


New submission from Eric Wieser <wieser.eric at gmail.com>:

The full definition of `multiprocessing.heap.BufferWrapper` is:

    class BufferWrapper(object):

        _heap = Heap()

        def __init__(self, size):
            if size < 0:
                raise ValueError("Size {0:n} out of range".format(size))
            if sys.maxsize <= size:
                raise OverflowError("Size {0:n} too large".format(size))
            block = BufferWrapper._heap.malloc(size)
            self._state = (block, size)
            util.Finalize(self, BufferWrapper._heap.free, args=(block,))

        def create_memoryview(self):
            (arena, start, stop), size = self._state
            return memoryview(arena.buffer)[start:start+size]


But this means that a `memoryview` can be constructed that point to free'd "memory",


    >>> b = BufferWrapper(10)
    >>> m = b.create_memoryview()
    >>> del b  # free is called
    >>> b[0]  # making this invalid

It would be better if `m` would keep a reference to `b` so that it remains alive.
`RawArray` works around this by placing a reference to `b` in `ctypes_obj._wrapper`, but this results in `b` being lost again if `m2 = memoryview(ctypes_obj); del ctypes_obj` is used.

----------
components: Library (Lib), ctypes
messages: 376149
nosy: Eric Wieser
priority: normal
severity: normal
status: open
title: Result of multiprocessing.heap.BufferWrapper.create_memoryview can point to freed memory
versions: Python 3.10, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41673>
_______________________________________


More information about the New-bugs-announce mailing list