Skip to content

Commit 8495af8

Browse files
GH-98897: fix memory leak if math.dist raises exception (GH-98898)
(cherry picked from commit ab57505) Co-authored-by: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
1 parent 46a3cf4 commit 8495af8

3 files changed

Lines changed: 9 additions & 3 deletions

File tree

Lib/test/test_math.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,6 +1006,11 @@ class T(tuple):
10061006
self.assertEqual(math.dist(p, q), 5*scale)
10071007
self.assertEqual(math.dist(q, p), 5*scale)
10081008

1009+
def test_math_dist_leak(self):
1010+
# gh-98897: Check for error handling does not leak memory
1011+
with self.assertRaises(ValueError):
1012+
math.dist([1, 2], [3, 4, 5])
1013+
10091014
def testIsqrt(self):
10101015
# Test a variety of inputs, large and small.
10111016
test_values = (
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix memory leak in :func:`math.dist` when both points don't have the same dimension. Patch by Kumar Aditya.

Modules/mathmodule.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2703,13 +2703,13 @@ math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
27032703
if (m != n) {
27042704
PyErr_SetString(PyExc_ValueError,
27052705
"both points must have the same number of dimensions");
2706-
return NULL;
2707-
2706+
goto error_exit;
27082707
}
27092708
if (n > NUM_STACK_ELEMS) {
27102709
diffs = (double *) PyObject_Malloc(n * sizeof(double));
27112710
if (diffs == NULL) {
2712-
return PyErr_NoMemory();
2711+
PyErr_NoMemory();
2712+
goto error_exit;
27132713
}
27142714
}
27152715
for (i=0 ; i<n ; i++) {

0 commit comments

Comments
 (0)