Skip to content

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

Merged
ngoldbaum merged 2 commits into
numpy: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 into
numpy: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

Thanks! Please also add a regression test.

@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

Thanks for the review and merge! I plan to keep contributing.

@Breno-Favaretto Breno-Favaretto deleted the fix-nditer-multi-index-segfault branch April 23, 2026 23:00
@charris charris removed the 09 - Backport-Candidate PRs tagged should be backported label Apr 26, 2026
charris added a commit that referenced this pull request Apr 26, 2026
BUG: Fix segfault in nditer.multi_index when __getitem__ raises (#31314)
MaanasArora pushed a commit to MaanasArora/numpy that referenced this pull request May 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants