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
This commit is contained in:
Haoran Peng 2025-05-01 22:04:59 +01:00 committed by Hennadii Stepanov
parent 5b8046a6e8
commit 2fd3f2fec6
No known key found for this signature in database
GPG Key ID: 410108112E7EA81F

View File

@ -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