BUG: Fix segfault in nditer.multi_index when __getitem__ raises by Breno-Favaretto · Pull Request #31314 · numpy/numpy · GitHub
Skip to content

BUG: Fix segfault in nditer.multi_index when __getitem__ raises#31314

Merged
ngoldbaum merged 2 commits intonumpy:mainfrom
Breno-Favaretto:fix-nditer-multi-index-segfault
Apr 23, 2026
Merged

BUG: Fix segfault in nditer.multi_index when __getitem__ raises#31314
ngoldbaum merged 2 commits intonumpy:mainfrom
Breno-Favaretto:fix-nditer-multi-index-segfault

Conversation

@Breno-Favaretto
Copy link
Copy Markdown
Contributor

PR summary

Add a NULL check for PySequence_GetItem in the multi_index setter to prevent
segmentation faults when getitem raises an exception.

As reported in:
https://gist.github.com/devdanzin/ccc2d9553ca1c90ab1835362ee21a40a#reproducer-3-nditermulti_index-segfault-with-raising-sequence
(discussed in #31046)

Reproduce error:

import numpy as np

class BadSequence:
    def __len__(self):
        return 2

    def __getitem__(self, i):
        if i == 1:
            raise RuntimeError("intentional error")
        return 0



arr = np.zeros((3, 4))
it = np.nditer(arr, flags=["multi_index"])

it.multi_index = BadSequence()

Actual behavior:

Segmentation fault         (core dumped)

Expected behavior:

RuntimeError: intentional error

First time committer introduction

AI Disclosure

AI tools were used to assist with English writing and phrasing in this PR.

The technical analysis, debugging, and code changes were performed and verified manually.

Check return value of PySequence_GetItem before use to avoid
dereferencing NULL and ensure Python exceptions are propagated.
@ngoldbaum
Copy link
Copy Markdown
Member

@ngoldbaum ngoldbaum added this to the 2.4.5 release milestone Apr 23, 2026
@ngoldbaum ngoldbaum added the 09 - Backport-Candidate PRs tagged should be backported label Apr 23, 2026
@ngoldbaum
Copy link
Copy Markdown
Member

Thanks @Breno-Favaretto. Please feel free to send in more fixes like this, if you feel like it.

@ngoldbaum ngoldbaum merged commit fa6d674 into numpy:main Apr 23, 2026
86 checks passed
@Breno-Favaretto
Copy link
Copy Markdown
Contributor Author

@Breno-Favaretto Breno-Favaretto deleted the fix-nditer-multi-index-segfault branch April 23, 2026 23:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

00 - Bug 09 - Backport-Candidate PRs tagged should be backported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants