我試圖避免Valgrind的誤報,但我吸了atexit()
和fork()
的組合,儘管使用--trace-children=yes
。我的代碼:valgrind --trace-children =是報告儘管atexit清理泄漏
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
static int * arr;
static void cleanup() {
free(arr);
printf("free arr as: %p\n", (void *)arr);
}
int main()
{
arr = malloc(16 * sizeof(int));
printf("allocated arr as: %p\n", (void *)arr);
atexit(cleanup);
pid_t pid = fork();
if (pid == -1) {
exit(1);
} else if (pid == 0) {
// child
_exit(0);
} else {
// parent
exit(0);
}
}
命令行:
$ clang -Weverything leak.c
$ valgrind --trace-children=yes ./a.out
==3287== Memcheck, a memory error detector
==3287== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==3287== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==3287== Command: ./a.out
==3287==
allocated arr as: 0x5202040
free arr as: 0x5202040
==3288==
==3288== HEAP SUMMARY:
==3288== in use at exit: 64 bytes in 1 blocks
==3288== total heap usage: 2 allocs, 1 frees, 1,088 bytes allocated
==3288==
==3288== LEAK SUMMARY:
==3288== definitely lost: 0 bytes in 0 blocks
==3288== indirectly lost: 0 bytes in 0 blocks
==3288== possibly lost: 0 bytes in 0 blocks
==3288== still reachable: 64 bytes in 1 blocks
==3288== suppressed: 0 bytes in 0 blocks
==3288== Rerun with --leak-check=full to see details of leaked memory
==3288==
==3288== For counts of detected and suppressed errors, rerun with: -v
==3288== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==3287==
==3287== HEAP SUMMARY:
==3287== in use at exit: 0 bytes in 0 blocks
==3287== total heap usage: 2 allocs, 2 frees, 1,088 bytes allocated
==3287==
==3287== All heap blocks were freed -- no leaks are possible
==3287==
==3287== For counts of detected and suppressed errors, rerun with: -v
==3287== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
基礎上printf()
輸出,它看起來像有沒有泄漏。我可以說服valgrind這個,或者我應該只是將其添加到我的valgrind抑制文件?
謝謝!是的,我確實誤解了'fork()'的「父母地址空間副本」部分。爲了幫助任何人在未來絆倒這個問題,請谷歌「虛擬地址空間」和/或閱讀:http://stackoverflow.com/a/5365635/7541781 – gperciva