Skip to content

Commit f4eca5d

Browse files
committed
fix list access
1 parent e799891 commit f4eca5d

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

selectlib.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,19 @@ less_than(PyObject *a, PyObject *b)
3232
/*
3333
Swap the elements at indices i and j in the Python list.
3434
If keys is not NULL, also swap the corresponding keys.
35+
This version uses the official Python C-API (PyList_GetItem/PyList_SetItem)
36+
to avoid direct access to the ob_item field.
3537
*/
3638
static void
3739
swap_items(PyObject *list, Py_ssize_t i, Py_ssize_t j, PyObject **keys)
3840
{
39-
PyListObject *lst = (PyListObject *)list;
40-
PyObject *temp = lst->ob_item[i];
41-
lst->ob_item[i] = lst->ob_item[j];
42-
lst->ob_item[j] = temp;
41+
PyObject *temp = PyList_GetItem(list, i);
42+
Py_INCREF(temp);
43+
PyObject *item_j = PyList_GetItem(list, j);
44+
Py_INCREF(item_j);
45+
46+
PyList_SetItem(list, i, item_j); /* Steals reference of item_j */
47+
PyList_SetItem(list, j, temp); /* Steals reference of temp */
4348

4449
if (keys != NULL) {
4550
PyObject *temp_key = keys[i];

0 commit comments

Comments
 (0)