[英]Memory leak found with Valgrind but I can't understand it
提前感謝您的關注。 我正在為一個項目編寫一個模擬程序,但是當我使用valgrind時,我的“骨架”會出現釋放問題。
程序說明:程序迭代,直到用戶使用SIGINT或SIGTERM停止它。 它使用兩個線程,一個用於計算(收集器),另一個用於處理信號(sighandler)。
一旦其中一個信號到達,程序就等待當前迭代完成然后退出。 為此,我使用了一個由sighandler更改的全局整數(status),並且每次迭代結束時都會檢查收集器。 我使用互斥鎖來保護變量。 這是代碼:
void* sighandler(void *arg);
void* collector(void *arg);
int status = 0;
int counter = 0;
pthread_t t_sighand, t_collector;
pthread_mutex_t mtx_status = PTHREAD_MUTEX_INITIALIZER;
sigset_t set;
int main(int argc, char *argv[]) {
/* Blocking signals */
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
pthread_sigmask(SIG_SETMASK, &set, NULL);
/* Threads creation */
pthread_create(&t_sighand, NULL, &sighandler, NULL);
pthread_create(&t_collector, NULL, &collector, NULL);
/* Waiting threads to end */
pthread_join(t_collector, NULL);
pthread_join(t_sighand, NULL);
exit(EXIT_SUCCESS);
}
void* sighandler(void *arg) {
int sig;
/* Waiting signals */
while(TRUE) {
sigwait(&set, &sig);
if( (sig == SIGINT) || (sig == SIGTERM) ) {
/* Change of status to notify the signal received */
pthread_mutex_lock(&mtx_status);
status = -1;
pthread_mutex_unlock(&mtx_status);
pthread_exit(NULL);
}
}
}
void* collector(void *arg) {
while(TRUE) {
/* Here I'll do all the stuff */
/* At the end I check to see if I need to stop */
pthread_mutex_lock(&mtx_status);
if(status == -1) {
pthread_mutex_unlock(&mtx_status);
pthread_exit(NULL);
}
pthread_mutex_unlock(&mtx_status);
counter++;
}
}
當我嘗試用valgrind運行它時,我得到了這個結果:
==3293== HEAP SUMMARY:
==3293== in use at exit: 990 bytes in 4 blocks
==3293== total heap usage: 7 allocs, 3 frees, 1,290 bytes allocated
==3293==
==3293== LEAK SUMMARY:
==3293== definitely lost: 0 bytes in 0 blocks
==3293== indirectly lost: 0 bytes in 0 blocks
==3293== possibly lost: 0 bytes in 0 blocks
==3293== still reachable: 990 bytes in 4 blocks
==3293== suppressed: 0 bytes in 0 blocks
==3293== Rerun with --leak-check=full to see details of leaked memory
==3293==
==3293== For counts of detected and suppressed errors, rerun with: -v
==3293== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
我發現如果我刪除收集器沒有內存泄漏,但我不明白收集器中的問題可能在哪里。 你能幫助我嗎? :(
再次感謝您的關注和幫助!
在我嘗試的至少一個系統(FreeBSD)上,標准I / O緩沖區使用malloc。 特別是,可以動態分配stdout
的緩沖區。 我得到一個干凈的清潔valgrind結果,直到我在main()
完成之前fclose(stdout)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.