我有一个程序应该启动一个线程。为了避免退出软件,线程在无限循环中运行,我加入了线程。这个线程永远不应该返回一个值。所以现在我有一个问题,在我调用 pthread_cancel valgrind 后检测到内存泄漏。如何避免这种内存泄漏?
Valgrind 输出:
==5673== 136 bytes in 1 blocks are possibly lost in loss record 4 of 8
==5673== at 0x4026A68: calloc (vg_replace_malloc.c:566)
==5673== by 0x40111FB: _dl_allocate_tls (dl-tls.c:300)
==5673== by 0x404E5A0: pthread_create@@GLIBC_2.1 (allocatestack.c:580)
==5673== by 0x804C44E: start (mythread.c:25)
==5673== by 0x804D128: main (main.c:10)
代码:
int main(){
signal(SIGINT,cleanup);
signal(SIGQUIT,cleanup);
signal(SIGSEGV,cleanup);
start();
return 0;
}
int start()
{
pthread_create(&thread_id[0],NULL,&threadhandler,NULL);
pthread_join(thread_id[0],NULL);
return err;
}
void cleanup(){
pthread_cancel(thread_id[0]);
exit(0);
}
void cleanup_tcp(void *p){
}
void* threadhandler(void *arg)
{
(void) arg;
int status = 0;
while(TRUE){
pthread_cleanup_push(cleanup_tcp,NULL);
pthread_testcancel();
fprintf(stderr,"Run\n");
pthread_cleanup_pop(0);
}
return NULL;
}