]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-98897: fix memory leak if `math.dist` raises exception (GH-98898)
authorKumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
Tue, 1 Nov 2022 02:18:32 +0000 (07:48 +0530)
committerGitHub <noreply@github.com>
Tue, 1 Nov 2022 02:18:32 +0000 (21:18 -0500)
Lib/test/test_math.py
Misc/NEWS.d/next/Library/2022-10-31-12-34-03.gh-issue-98897.rgNn4x.rst [new file with mode: 0644]
Modules/mathmodule.c

index cfaf3b3ea26a7ed80be59cacab3edfb20f5a88a2..bf0d0a56e6ac8b39e897fab24fc2aaceb3250821 100644 (file)
@@ -1006,6 +1006,11 @@ class MathTests(unittest.TestCase):
             self.assertEqual(math.dist(p, q), 5*scale)
             self.assertEqual(math.dist(q, p), 5*scale)
 
+    def test_math_dist_leak(self):
+        # gh-98897: Check for error handling does not leak memory
+        with self.assertRaises(ValueError):
+            math.dist([1, 2], [3, 4, 5])
+
     def testIsqrt(self):
         # Test a variety of inputs, large and small.
         test_values = (
diff --git a/Misc/NEWS.d/next/Library/2022-10-31-12-34-03.gh-issue-98897.rgNn4x.rst b/Misc/NEWS.d/next/Library/2022-10-31-12-34-03.gh-issue-98897.rgNn4x.rst
new file mode 100644 (file)
index 0000000..f61af25
--- /dev/null
@@ -0,0 +1 @@
+Fix memory leak in :func:`math.dist` when both points don't have the same dimension. Patch by Kumar Aditya.
index 48625c8c18d70e2a4e5215f30089919e9df57a0a..46427876b8f4b58c7b64684e7310be311c02e681 100644 (file)
@@ -2717,13 +2717,13 @@ math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
     if (m != n) {
         PyErr_SetString(PyExc_ValueError,
                         "both points must have the same number of dimensions");
-        return NULL;
-
+        goto error_exit;
     }
     if (n > NUM_STACK_ELEMS) {
         diffs = (double *) PyObject_Malloc(n * sizeof(double));
         if (diffs == NULL) {
-            return PyErr_NoMemory();
+            PyErr_NoMemory();
+            goto error_exit;
         }
     }
     for (i=0 ; i<n ; i++) {