You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BUG: File descriptor leak in npy_PyFile_Dup2 when fdopen fails #32373
In numpy/_core/include/numpy/npy_3kcompat.h, the function npy_PyFile_Dup2 (used by numpy.fromfile and ndarray.tofile) has a file descriptor leak on an error path.
When os.dup() succeeds but the subsequent fdopen() call fails, the duplicated file descriptor fd2 is never closed. The code sets a Python error and returns NULL without calling close(fd2):
// npy_3kcompat.h, around line 113-127#ifdef_WIN32NPY_BEGIN_SUPPRESS_IPHhandle=_fdopen(fd2, mode);
NPY_END_SUPPRESS_IPH#elsehandle=fdopen(fd2, mode);
#endifif (handle==NULL) {
PyErr_SetString(PyExc_IOError,
"Getting a FILE* from a Python file object via ""_fdopen failed. If you built NumPy, you probably ""linked with the wrong debug/release runtime");
returnNULL; // <-- fd2 is leaked here
}
All other error paths after fdopen succeeds properly call fclose(handle), so this is the only leak.
Reproduce the code example:
Addaplatform-appropriaterawfdclosebeforereturning`NULL`:
if (handle==NULL) {
+#ifdef _WIN32+_close(fd2);
+#else+close(fd2);
+#endifPyErr_SetString(PyExc_IOError,
"Getting a FILE* from a Python file object via ""_fdopen failed. If you built NumPy, you probably ""linked with the wrong debug/release runtime");
returnNULL;
}
Note: `fclose`cannotbeusedherebecause`fdopen`failed, sothereisnovalid`FILE*`handle — onlytherawfiledescriptor`fd2`needstobecleanedup.
Activity
ngoldbaum commentedon Aug 21, 2026
Just go ahead and open PRs for small C API bugs like this. No need to go through the ceremony of an issue.