diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-21-21-26-10.gh-issue-159739.Zw43uX.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-21-21-26-10.gh-issue-159739.Zw43uX.rst new file mode 100644 index 000000000000000..628a146b059a436 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-21-21-26-10.gh-issue-159739.Zw43uX.rst @@ -0,0 +1 @@ +Raise :exc:`MemoryError` instead of returning an incorrect result if :func:`round` runs out of memory while rounding a float. diff --git a/Objects/floatobject.c b/Objects/floatobject.c index d5a879cdd53ad62..c19ed6e6b609352 100644 --- a/Objects/floatobject.c +++ b/Objects/floatobject.c @@ -942,11 +942,16 @@ double_round(double x, int ndigits) { _Py_SET_53BIT_PRECISION_START; rounded = _Py_dg_strtod(mybuf, NULL); _Py_SET_53BIT_PRECISION_END; - if (errno == ERANGE && fabs(rounded) >= 1.) + if (errno == ENOMEM) { + PyErr_NoMemory(); + } + else if (errno == ERANGE && fabs(rounded) >= 1.) { PyErr_SetString(PyExc_OverflowError, "rounded value too large to represent"); - else + } + else { result = PyFloat_FromDouble(rounded); + } /* done computing value; now clean up */ if (mybuf != shortbuf)