我有一個簡單的程序創建一個線程,並等待線程結束時,然後程序也結束。當我用C(gcc)編譯器編譯這個程序,並用valgrind檢查它時,沒有發生問題,但是當我用C++(g ++)編譯器編譯它並檢查valgrind時,它顯示我的程序有內存泄漏。可能是什麼問題呢?內存泄漏問題
這是我的計劃,
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
unsigned char b = 0;
void* threadfunc1(void *pVoid)
{
while(b == 0)
{
usleep(10000);
}
pthread_exit(0);
}
int main(void)
{
int status;
pthread_attr_t tattr;
pthread_t thread1;
status = pthread_attr_init(&tattr);
status = pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_JOINABLE);
status = pthread_attr_setscope(&tattr,PTHREAD_SCOPE_SYSTEM);
if(pthread_create(&thread1, &tattr, threadfunc1, NULL) != 0)
{
exit(1);
}
usleep(1000000);
b = 1;
pthread_join(thread1, NULL);
usleep(2000000);
return 0;
}
這就是結果,當我編譯它用G ++,並在Valgrind的檢查
==7658== HEAP SUMMARY:
==7658== in use at exit: 28 bytes in 1 blocks
==7658== total heap usage: 2 allocs, 1 frees, 172 bytes allocated
==7658==
==7658== 28 bytes in 1 blocks are still reachable in loss record 1 of 1
==7658== at 0x4024C1C: malloc (vg_replace_malloc.c:195)
==7658== by 0x400C01E: _dl_map_object_deps (dl-deps.c:506)
==7658== by 0x40117E0: dl_open_worker (dl-open.c:297)
==7658== by 0x400D485: _dl_catch_error (dl-error.c:178)
==7658== by 0x401119F: _dl_open (dl-open.c:586)
==7658== by 0x428D0C1: do_dlopen (dl-libc.c:86)
==7658== by 0x400D485: _dl_catch_error (dl-error.c:178)
==7658== by 0x428D1C0: dlerror_run (dl-libc.c:47)
==7658== by 0x428D2DA: __libc_dlopen_mode (dl-libc.c:160)
==7658== by 0x4048876: pthread_cancel_init (unwind-forcedunwind.c:53)
==7658== by 0x40489EC: _Unwind_ForcedUnwind (unwind-forcedunwind.c:126)
==7658== by 0x40464B7: __pthread_unwind (unwind.c:130)
==7658==
==7658== LEAK SUMMARY:
==7658== definitely lost: 0 bytes in 0 blocks
==7658== indirectly lost: 0 bytes in 0 blocks
==7658== possibly lost: 0 bytes in 0 blocks
==7658== still reachable: 28 bytes in 1 blocks
==7658== suppressed: 0 bytes in 0 blocks
那麼,究竟我做錯了,是它我的錯誤或...,爲什麼當我用gcc編譯它時沒有發生問題,當我使用C++編譯它時,內存泄漏是存在的?
編寫多語言的源文件是很難的。預計會有更多問題。我建議你只使用C或C++中的一種。 – pmg 2011-06-13 08:40:01
我從我的朋友那裏得到這個程序,他通過makefile編譯它,但是我爲這個程序在NetBeans中創建了一個新項目,因爲我的默認編譯器是gcc,編譯和運行時我沒有問題,但是當我通過makefile編譯它時,我有這個泄漏,所以知道這是爲什麼很有趣? – akmal 2011-06-13 09:02:06