我编写的程序有时会在其子进程中泄漏。为了找出原因,我跑了
valgrind --leak-check=full --trace-children=yes ./shell
它--leak-check=full在父进程上正常工作,但明确不适用于任何子进程。例如,
==14044== Memcheck, a memory error detector
==14044== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==14044== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==14044== Command: ./shell
==14044==
Shell by: user
(pid=14044)/home/user/user/shell$ invalid_command --flag-that-is-ignored
Command executed by pid=14044
invalid_command: not found
==14046==
==14046== HEAP SUMMARY:
==14046== in use at exit: 120 bytes in 1 blocks
==14046== total heap usage: 16 allocs, 15 frees, 552 bytes allocated
==14046==
==14046== LEAK SUMMARY:
==14046== definitely lost: 0 bytes in 0 blocks
==14046== indirectly lost: 0 bytes in 0 blocks
==14046== possibly lost: 0 bytes in 0 blocks
==14046== still reachable: 120 bytes in 1 blocks
==14046== suppressed: 0 bytes in 0 blocks
==14046== Reachable blocks (those to which a pointer was found) are not shown.
==14046== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==14046==
==14046== For counts of detected and suppressed errors, rerun with: -v
==14046== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
(pid=14044)/home/user/user/shell$ exit
==14044==
==14044== HEAP SUMMARY:
==14044== in use at exit: 0 bytes in 0 blocks
==14044== total heap usage: 26 allocs, 26 frees, 845 bytes allocated
==14044==
==14044== All heap blocks were freed -- no leaks are possible
==14044==
==14044== For counts of detected and suppressed errors, rerun with: -v
==14044== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,当我invalid_command从程序中调用时,它正确地认为这invalid_command不是命令并相应地打印错误。然后,该子进程清理并退出,并且 valgrind 打印出泄漏摘要。但泄漏摘要表明rerun with: --leak-check=full,尽管我确实使用该标志运行了它!
当我退出父进程时,没有内存泄漏,并且似乎--leak-check=full正确地应用于父进程。
如何才能--leak-check=full应用于我创建的子进程?该程序是用 C 编写的,我只是使用正常的fork(); exec(); wait();范例。
小智 5
以下选项组合解决了我的问题:
valgrind --leak-check=full --show-leak-kinds=all --trace-children=yes ./shell
如果省略其中任何一个,输出将如上所示(不包括行号)。