Skip to content

gh-148484: Fix memory leak of iterator in array.array constructor#148523

Open
gleb-pp wants to merge 7 commits intopython:mainfrom
gleb-pp:main
Open

gh-148484: Fix memory leak of iterator in array.array constructor#148523
gleb-pp wants to merge 7 commits intopython:mainfrom
gleb-pp:main

Conversation

@gleb-pp
Copy link
Copy Markdown
Contributor

@gleb-pp gleb-pp commented Apr 13, 2026

Fix memory leak of iterator in array.array constructor

When array.array is initialized with an arbitrary iterable, an iterator is created via PyObject_GetIter().

If an invalid typecode is provided, the constructor raises a ValueError without decref'ing the iterator, leading to a memory leak.

This patch fixes the issue by adding a missing Py_XDECREF(it) before returning the ValueError.

The issue affects the fallback iterable initialization path only.
Fast-path initializers (list, tuple, bytes, bytearray, array, str) are not affected.

Copy link
Copy Markdown
Member

@skirpichev skirpichev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This patch ensures that the iterator is correctly DECREF'ed on all error paths after it is created.

That's not true, you ignored some case. For example, shown in the issue thread.

@gleb-pp
Copy link
Copy Markdown
Contributor Author

gleb-pp commented Apr 14, 2026

This patch ensures that the iterator is correctly DECREF'ed on all error paths after it is created.

That's not true, you ignored some case. For example, shown in the issue thread.

You're right. My previous patch missed some error paths after PyObject_GetIter().

I've updated the patch to handle the invalid typecode case (as discussed in the issue), and also added a DECREF when newarrayobject() fails, so the iterator is not leaked in these scenarios.

Please let me know if you'd prefer the fix to be limited strictly to the invalid typecode path.

@gleb-pp gleb-pp requested a review from skirpichev April 14, 2026 08:38
@gleb-pp gleb-pp requested a review from skirpichev April 14, 2026 08:54
Copy link
Copy Markdown
Member

@skirpichev skirpichev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

One minor suggestion, up to other reviewers discretion.

Comment on lines 3067 to 3069
Py_DECREF(a);
Py_XDECREF(it);
return NULL;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a common part for most cleanups. You can add a label and use goto statements in other places.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants