Skip to content

PyObject_CopyData() copies wrong data, and can corrupt memory, when source and destination shapes differ and the source is not contiguous #161081

Open

Description

@Davien21

Bug report

I ran into this while writing tests for PyObject_CopyData() in GH-160701.

In the strided path of PyObject_CopyData() (Objects/abstract.c), the loop walks the source's indices and passes the same indices array to PyBuffer_GetPointer(&view_dest, ...). If the destination has a different shape, elements land at the wrong offsets. If it has more dimensions than the source, PyBuffer_GetPointer reads past the indices array.

Repro on 3.13.18 (numpy only to get a non-contiguous 2-D buffer; the code is unchanged on main):

import ctypes, numpy as np
f = ctypes.pythonapi.PyObject_CopyData
f.argtypes = [ctypes.py_object, ctypes.py_object]
src = np.arange(12, dtype=np.uint8).reshape(3, 4)[::2, ::2]
dest = bytearray(4)
print(f(dest, src), list(dest))   # 0 [0, 10, 0, 0], expected [0, 2, 8, 10]

dest = np.zeros((2, 4), np.uint8)
f(dest, memoryview(bytes(range(16)))[::2])   # returns 0, wrong data, then segfaults at exit

I'd like to send a fix. Two options: raise BufferError when the shapes differ outside the contiguous fast path, or copy element-wise in C order with separate index walks for dest and src. Which would you prefer? gh-153689 touches the same function.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Activity

  1. picnixz commented on Nov 1, 2026

    @picnixz
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-C-APItype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions