Skip to content

Iterating over ctypes pointer causes hang or segmentation fault #92347

Open
@chgnrdv

Description

@chgnrdv

Trying to create iterable (list, tuple, set etc.) from PyCPointer instance leads to hang or segmentation fault.
This code causes hang and memory leak which goes until oom-killer kills python process:

import ctypes
x = ctypes.c_int32(12345)
buf4_p_t = ctypes.POINTER(ctypes.ARRAY(ctypes.c_byte, 4))
buf_p = ctypes.cast(ctypes.byref(x), buf4_p_t)
list(buf_p)

Similar code that causes segmentation fault:

import ctypes
x = ctypes.c_int32(54321)
xp = ctypes.pointer(x)
list(xp)

Iterating over pointer using for statement leads to an infinite loop:
for i in buf_p: print(i)
for i in xp: print(i)
list(for i in buf_p)

Tried on 3.10.3 and 3.11.0a6+, fails at both.

The possible reason is that PyCPointer_Type defines sq_item without defining tp_iter.
Despite I can't imagine any reason why anyone might need to use pointer as iterable/sequence, raising TypeError in such situation would be a better option.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions