Skip to content

gh-151815: Fix segfault in template_iter on allocation failure#151821

Open
timurmamedov1 wants to merge 1 commit into
python:mainfrom
timurmamedov1:gh-151815-fix-template-iter-segfault
Open

gh-151815: Fix segfault in template_iter on allocation failure#151821
timurmamedov1 wants to merge 1 commit into
python:mainfrom
timurmamedov1:gh-151815-fix-template-iter-segfault

Conversation

@timurmamedov1

Copy link
Copy Markdown

template_iter() allocates a templateiterobject with PyObject_GC_New (which does not zero memory), but only assigns stringsiter and interpolationsiter after both PyObject_GetIter calls succeed. If either call fails, Py_DECREF(iter) runs templateiter_clear, which calls Py_CLEAR on uninitialized pointers, causing a segfault.

Fix: initialize both fields to NULL immediately after allocation so Py_CLEAR is safe on the error paths.

Initialize stringsiter and interpolationsiter to NULL immediately
after PyObject_GC_New so that templateiter_clear can safely run
Py_CLEAR if a subsequent PyObject_GetIter call fails.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Fixes a crash in the C implementation of t-string Template iteration by making the iterator object safe to deallocate when construction fails partway through (e.g., on PyObject_GetIter() allocation failure).

Changes:

  • Initialize templateiterobject’s stringsiter and interpolationsiter to NULL immediately after PyObject_GC_New() so tp_clear/Py_CLEAR is safe on error paths.
  • Add a NEWS blurb documenting the crash fix.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
Objects/templateobject.c Prevents segfault by NULL-initializing iterator fields before any fallible operations.
Misc/NEWS.d/next/Core_and_Builtins/2026-06-20-14-00-00.gh-issue-151815.TmplIt.rst Documents the crash fix in the Core and Builtins NEWS entries.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread Objects/templateobject.c
Comment on lines 222 to +230
template_iter(PyObject *op)
{
templateobject *self = templateobject_CAST(op);
templateiterobject *iter = PyObject_GC_New(templateiterobject, &_PyTemplateIter_Type);
if (iter == NULL) {
return NULL;
}
iter->stringsiter = NULL;
iter->interpolationsiter = NULL;
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