[英]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.