Skip to content

Commit de72edd

Browse files
committed
Fixup error exits in nlargest() and nsmallest().
1 parent bb6b734 commit de72edd

1 file changed

Lines changed: 16 additions & 8 deletions

File tree

‎Modules/_heapqmodule.c‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,17 @@ nlargest(PyObject *self, PyObject *args)
230230
return NULL;
231231

232232
heap = PyList_New(0);
233-
if (it == NULL)
233+
if (heap == NULL)
234234
goto fail;
235235

236236
for (i=0 ; i<n ; i++ ){
237237
elem = PyIter_Next(it);
238-
if (elem == NULL)
239-
goto sortit;
238+
if (elem == NULL) {
239+
if (PyErr_Occurred())
240+
goto fail;
241+
else
242+
goto sortit;
243+
}
240244
if (PyList_Append(heap, elem) == -1) {
241245
Py_DECREF(elem);
242246
goto fail;
@@ -271,11 +275,11 @@ nlargest(PyObject *self, PyObject *args)
271275
sol = PyList_GET_ITEM(heap, 0);
272276
}
273277
sortit:
274-
Py_DECREF(it);
275278
if (PyList_Sort(heap) == -1)
276279
goto fail;
277280
if (PyList_Reverse(heap) == -1)
278281
goto fail;
282+
Py_DECREF(it);
279283
return heap;
280284

281285
fail:
@@ -385,13 +389,17 @@ nsmallest(PyObject *self, PyObject *args)
385389
return NULL;
386390

387391
heap = PyList_New(0);
388-
if (it == NULL)
392+
if (heap == NULL)
389393
goto fail;
390394

391395
for (i=0 ; i<n ; i++ ){
392396
elem = PyIter_Next(it);
393-
if (elem == NULL)
394-
goto sortit;
397+
if (elem == NULL) {
398+
if (PyErr_Occurred())
399+
goto fail;
400+
else
401+
goto sortit;
402+
}
395403
if (PyList_Append(heap, elem) == -1) {
396404
Py_DECREF(elem);
397405
goto fail;
@@ -429,9 +437,9 @@ nsmallest(PyObject *self, PyObject *args)
429437
}
430438

431439
sortit:
432-
Py_DECREF(it);
433440
if (PyList_Sort(heap) == -1)
434441
goto fail;
442+
Py_DECREF(it);
435443
return heap;
436444

437445
fail:

0 commit comments

Comments
 (0)