From 9b6521198c4f31d3f9cb525e581bea8e3e77f0a2 Mon Sep 17 00:00:00 2001
From: Ralf Gommers <ralf.gommers@gmail.com>
Date: Mon, 13 Jun 2022 20:12:00 +0200
Subject: [PATCH] BUG: fix a minor refcounting issue in `Py_FindObjects`

Closes gh-16235

Note: also change `Py_XDECREF`s for start/end variables to `Py_DECREF`,
because it's already checked higher up that those variables are not
NULL.

Reference: https://github.com/scipy/scipy/pull/16397/commits/9b6521198c4f31d3f9cb525e581bea8e3e77f0a2
Conflict: NA
---
 scipy/ndimage/src/nd_image.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/scipy/ndimage/src/nd_image.c b/scipy/ndimage/src/nd_image.c
index 8dfa21ea2..11d176a30 100644
--- a/scipy/ndimage/src/nd_image.c
+++ b/scipy/ndimage/src/nd_image.c
@@ -885,7 +885,7 @@ static PyObject *Py_FindObjects(PyObject *obj, PyObject *args)
         npy_intp idx =
                 PyArray_NDIM(input) > 0 ? 2 * PyArray_NDIM(input) * ii : ii;
         if (regions[idx] >= 0) {
-            PyObject *tuple = PyTuple_New(PyArray_NDIM(input));
+            tuple = PyTuple_New(PyArray_NDIM(input));
             if (!tuple) {
                 PyErr_NoMemory();
                 goto exit;
@@ -903,8 +903,8 @@ static PyObject *Py_FindObjects(PyObject *obj, PyObject *args)
                     PyErr_NoMemory();
                     goto exit;
                 }
-                Py_XDECREF(start);
-                Py_XDECREF(end);
+                Py_DECREF(start);
+                Py_DECREF(end);
                 start = end = NULL;
                 PyTuple_SetItem(tuple, jj, slc);
                 slc = NULL;
-- 
2.33.0

