From 2fd3f2fec67a3bb62378c286fbf9667e6fb3cc3b Mon Sep 17 00:00:00 2001 From: Haoran Peng Date: Thu, 1 May 2025 22:04:59 +0100 Subject: [PATCH] subprocess: Fix memory leaks I encountered this issue while running my code with Valgrind today. Below is part of the Valgrind error message: ``` ==1578139== 472 bytes in 1 blocks are still reachable in loss record 1 of 1 ==1578139== at 0x4848899: malloc (...) ==1578139== by 0x4B3AF62: fdopen@@GLIBC_2.2.5 (...) ==1578139== by 0x118B09: subprocess::Popen::execute_process() (...) ``` I noticed that a similar fix had been proposed by another contributor previously. I did not mean to scoop their work, but merely hoping to fix it sooner so other people don't get confused by it just as I did today. Github-Pull: arun11299/cpp-subprocess#106 Rebased-From: 3afe581c1f22f106d59cf54b9b65251e6c554671 --- src/util/subprocess.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/util/subprocess.h b/src/util/subprocess.h index 3449fa3b1b..26651d3ae5 100644 --- a/src/util/subprocess.h +++ b/src/util/subprocess.h @@ -1181,11 +1181,13 @@ inline void Popen::execute_process() noexcept(false) try { char err_buf[SP_MAX_ERR_BUF_SIZ] = {0,}; - int read_bytes = util::read_atmost_n( - fdopen(err_rd_pipe, "r"), - err_buf, - SP_MAX_ERR_BUF_SIZ); - close(err_rd_pipe); + FILE* err_fp = fdopen(err_rd_pipe, "r"); + if (!err_fp) { + close(err_rd_pipe); + throw OSError("fdopen failed", errno); + } + int read_bytes = util::read_atmost_n(err_fp, err_buf, SP_MAX_ERR_BUF_SIZ); + fclose(err_fp); if (read_bytes || strlen(err_buf)) { // Call waitpid to reap the child process