mirror of
https://github.com/python/cpython.git
synced 2025-11-24 20:30:18 +00:00
[3.14] gh-140067: Fix memory leak in sub-interpreter creation (GH-140111) (#140118)
* [3.14] gh-140067: Fix memory leak in sub-interpreter creation (GH-140111)
Fix memory leak in sub-interpreter creation caused by overwriting of the previously used `_malloced` field. Now the pointer is stored in the first word of the memory block to avoid it being overwritten accidentally.
(cherry picked from commit 59547a251f)
Co-authored-by: Shamil <ashm.tech@proton.me>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
This commit is contained in:
parent
3ca7ea1f8f
commit
1d11627ba5
4 changed files with 12 additions and 10 deletions
|
|
@ -565,16 +565,19 @@ _PyInterpreterState_Enable(_PyRuntimeState *runtime)
|
|||
static PyInterpreterState *
|
||||
alloc_interpreter(void)
|
||||
{
|
||||
// Aligned allocation for PyInterpreterState.
|
||||
// the first word of the memory block is used to store
|
||||
// the original pointer to be used later to free the memory.
|
||||
size_t alignment = _Alignof(PyInterpreterState);
|
||||
size_t allocsize = sizeof(PyInterpreterState) + alignment - 1;
|
||||
size_t allocsize = sizeof(PyInterpreterState) + sizeof(void *) + alignment - 1;
|
||||
void *mem = PyMem_RawCalloc(1, allocsize);
|
||||
if (mem == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
PyInterpreterState *interp = _Py_ALIGN_UP(mem, alignment);
|
||||
assert(_Py_IS_ALIGNED(interp, alignment));
|
||||
interp->_malloced = mem;
|
||||
return interp;
|
||||
void *ptr = _Py_ALIGN_UP((char *)mem + sizeof(void *), alignment);
|
||||
((void **)ptr)[-1] = mem;
|
||||
assert(_Py_IS_ALIGNED(ptr, alignment));
|
||||
return ptr;
|
||||
}
|
||||
|
||||
static void
|
||||
|
|
@ -589,7 +592,7 @@ free_interpreter(PyInterpreterState *interp)
|
|||
interp->obmalloc = NULL;
|
||||
}
|
||||
assert(_Py_IS_ALIGNED(interp, _Alignof(PyInterpreterState)));
|
||||
PyMem_RawFree(interp->_malloced);
|
||||
PyMem_RawFree(((void **)interp)[-1]);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue