嘗試pclose()
以前用popen()
打開的管道時出現valgrind錯誤。錯誤發生在Mac OS X上,但不在Linux上。請看下面的例子:由Mac OS X上的pclose()引起的Valgrind錯誤
#include <stdlib.h>
#include <stdio.h>
int main() {
FILE *fp;
char buf[4096];
if (!(fp = popen("ls", "r")))
exit(-1);
while (fscanf(fp, "%s", buf) == 1)
printf("%s\n", buf);
pclose(fp);
return 0;
}
我得到的是Mac(OS X 10.6.7,Valgrind的版本3.6.0)以下Valgrind的錯誤,除非我刪除pclose()
電話:
==21455== Conditional jump or move depends on uninitialised value(s)
==21455== at 0xB1992: pclose (in /usr/lib/libSystem.B.dylib)
==21455== by 0x1F16: main (in ./a.out)
==21455==
==21455== Syscall param wait4(pid) contains uninitialised byte(s)
==21455== at 0x504FA: wait4 (in /usr/lib/libSystem.B.dylib)
==21455== by 0x1F16: main (in ./a.out)
但是,我在valgrind 3.5.0版的Linux系統上沒有發現任何錯誤。
關於什麼可能導致Mac上的錯誤的任何想法?
更新
中的valgrind打開--track-origins
表明,問題的根源可能在popen()
通話。用gcc 4.2.1和4.5.3得到了同樣的結果。
==4425== Conditional jump or move depends on uninitialised value(s)
==4425== at 0xB1992: pclose (in /usr/lib/libSystem.B.dylib)
==4425== by 0x1F18: main (in ./a.out)
==4425== Uninitialised value was created by a stack allocation
==4425== at 0xB14C5: popen$UNIX2003 (in /usr/lib/libSystem.B.dylib)
==4425==
==4425== Syscall param wait4(pid) contains uninitialised byte(s)
==4425== at 0x504FA: wait4 (in /usr/lib/libSystem.B.dylib)
==4425== by 0x1F18: main (in ./a.out)
==4425== Uninitialised value was created by a stack allocation
==4425== at 0xB14C5: popen$UNIX2003 (in /usr/lib/libSystem.B.dylib)
很難明白爲什麼它會這麼說。我有一種愚蠢的建議是在main()的第一行初始化你的fp爲NULL。 –
@Brian謝謝,但如你所說,初始化fp爲NULL後無效。 – Leo
您的代碼適用於我,也適用於Mac OS X v10.6.7和valgrind 3.6.0。我沒有看到你的代碼有任何問題 - 這可能沒有什麼可擔心的。 –