Skip to content

Commit 0bcb1c2

Browse files
Revert "gh-140067: Fix memory leak in sub-interpreter creation (#140111)" (#140140)
This reverts commit 59547a2.
1 parent 1e1f435 commit 0bcb1c2

File tree

3 files changed

+12
-10
lines changed

3 files changed

+12
-10
lines changed

Include/internal/pycore_interp_structs.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -769,6 +769,12 @@ struct _is {
769769
* and should be placed at the beginning. */
770770
struct _ceval_state ceval;
771771

772+
/* This structure is carefully allocated so that it's correctly aligned
773+
* to avoid undefined behaviors during LOAD and STORE. The '_malloced'
774+
* field stores the allocated pointer address that will later be freed.
775+
*/
776+
void *_malloced;
777+
772778
PyInterpreterState *next;
773779

774780
int64_t id;

Misc/NEWS.d/next/Core_and_Builtins/2025-10-14-17-07-37.gh-issue-140067.ID2gOm.rst

Lines changed: 0 additions & 1 deletion
This file was deleted.

Python/pystate.c

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -457,19 +457,16 @@ _PyInterpreterState_Enable(_PyRuntimeState *runtime)
457457
static PyInterpreterState *
458458
alloc_interpreter(void)
459459
{
460-
// Aligned allocation for PyInterpreterState.
461-
// the first word of the memory block is used to store
462-
// the original pointer to be used later to free the memory.
463460
size_t alignment = _Alignof(PyInterpreterState);
464-
size_t allocsize = sizeof(PyInterpreterState) + sizeof(void *) + alignment - 1;
461+
size_t allocsize = sizeof(PyInterpreterState) + alignment - 1;
465462
void *mem = PyMem_RawCalloc(1, allocsize);
466463
if (mem == NULL) {
467464
return NULL;
468465
}
469-
void *ptr = _Py_ALIGN_UP((char *)mem + sizeof(void *), alignment);
470-
((void **)ptr)[-1] = mem;
471-
assert(_Py_IS_ALIGNED(ptr, alignment));
472-
return ptr;
466+
PyInterpreterState *interp = _Py_ALIGN_UP(mem, alignment);
467+
assert(_Py_IS_ALIGNED(interp, alignment));
468+
interp->_malloced = mem;
469+
return interp;
473470
}
474471

475472
static void
@@ -484,7 +481,7 @@ free_interpreter(PyInterpreterState *interp)
484481
interp->obmalloc = NULL;
485482
}
486483
assert(_Py_IS_ALIGNED(interp, _Alignof(PyInterpreterState)));
487-
PyMem_RawFree(((void **)interp)[-1]);
484+
PyMem_RawFree(interp->_malloced);
488485
}
489486
}
490487

0 commit comments

Comments
 (0)