Iterating over ctypes pointer causes hang or segmentation fault
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
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
- gh-126318
- gh-157801
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the ctypes PyCPointer behavior shown in the two reproductions and confirm the hang, memory growth, and segmentation fault on the affected Python versions. Trace how pointer indexing and iteration interact, then verify that the completed behavior safely rejects iteration without hanging or crashing; linked PRs gh-126318 and gh-157801 provide existing work to inspect.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100