0

I'm seeing a strange issue. Sample code is included below

When this code is run with valgrind, it complains that the memory allocated with popen is still reachable. Should i worry about this warning? If yes, what is a possible solution?

       Func1()
            FILE *fp = NULL;
            int fd = 0;
            fp = popen(g_cmd, "r");
            fd = fileno(fp); // store fd for later processing.
            ...
    
       Func2(fd)
            FILE *popen_fp = NULL;
            popen_fp  = fdopen(fd, "r");  // Convert fd to File pointer.
            if (popen_fp) pclose(popen_fp);

==11748== 256 bytes in 1 blocks are still reachable in loss record 1 of 1
==11748==    at 0x4C29F73: malloc
==11748==    by 0x5542627: popen@@GLIBC_2.2.5
LEAK SUMMARY:
==11748==    definitely lost: 0 bytes in 0 blocks
==11748==    indirectly lost: 0 bytes in 0 blocks
==11748==      possibly lost: 0 bytes in 0 blocks
==11748==    still reachable: 256 bytes in 1 blocks
  • You can build your code with `-DGLIBCXX_FORCE_NEW` (if the name hasn't changed), to force the libc calls to free pools memory. Beware it can affect performance. – Zilog80 Jun 28 '21 at 09:09
  • A [previous answer](https://stackoverflow.com/questions/30376601/valgrind-memory-still-reachable-with-trivial-program-using-iostream) states also that it could be valgrind fault (in the way that valgrind shouldn't look further for allocations outside the main core of your process, before init). It seems it's not the case here. – Zilog80 Jun 28 '21 at 09:17
  • Also, `if (popen_fp) pclose(popen_fp);` should be `if (popen_fp) fclose(popen_fp);` as `fopen_fp` refers to a stream handle, no ? You can also use `fdclose` if you want to keep fd open. – Zilog80 Jun 28 '21 at 09:30

0 Answers0