Valgrind发现内存泄漏,但我无法理解

时间:2015-11-08 17:27:34

标签: c unix pthreads mutex valgrind

提前感谢您的关注。我正在为一个项目编写一个模拟程序,但是我的#"骨架有一个解除分配的问题。当我使用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)

我发现如果我删除收藏家那里没有内存泄漏,但我不明白收藏家的问题在哪里。你能帮助我吗? :(

再次感谢您的关注和帮助!

1 个答案:

答案 0 :(得分:0)

在我尝试的至少一个系统(FreeBSD)上,标准I / O缓冲区使用malloc。特别是,stdout的缓冲区可以动态分配。在fclose(stdout)完成之前,main()之前我得到了一个干净的valgrind结果。

相关问题