即使使用正确,Pthreads也会泄漏内存

时间:2015-01-06 17:21:07

标签: c memory-leaks pthreads valgrind

我一直在为此而奋斗。环顾四周,我似乎无法找到答案。我只是创建两个分离的线程,然后在它们两个上使用pthread_exit(),但偶尔会有泄漏。

因为我知道人们会问我:

  1. 是的,我已阅读所有其他问题而且没有真正的答案
  2. 我将主题标记为detached
  3. 我为enough time提供线程初始化和死亡
  4. 我已阅读pthread_exit手册并已正确使用
  5. 使用-Wall
  6. 编译好

    代码:

    int threads_keepalive = 1;
    
    void* thread_do(void *arg){
        while(threads_keepalive)
            sleep(1);
        pthread_exit(NULL);
    }
    
    int main(){
    
        /* Make threads */
        pthread_t* threads;
        threads = malloc(2 * sizeof(pthread_t));
        pthread_create(&threads[0], NULL, thread_do, NULL);
        pthread_create(&threads[1], NULL, thread_do, NULL);
        pthread_detach(threads[0]);
        pthread_detach(threads[1]);
        sleep(1); // MAKING SURE THREADS HAVE INITIALIZED
    
        /* Kill threads */
        threads_keepalive = 0;
        sleep(5); // MAKING SURE THREADS HAVE UNBLOCKED
        free(threads);
    
        return 0;
    }
    

    运行该代码,虽然它是正确的(至少在我看来),我随机时间会出现内存泄漏。我使用valgrind多次运行相同的测试,如下所示

    > gcc test.c -pthread -o test && for i in {1..100}; do valgrind --leak-check=full --track-origins=yes ./test 2>&1 | grep frees; done
    ==4088==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
    ==4211==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
    ==4337==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
    ==4463==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
    ==4590==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
    ==4717==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
    ==4853==   total heap usage: 8 allocs, 4 frees, 2,230 bytes allocated
    ==4981==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
    ==5110==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
    ==5239==   total heap usage: 8 allocs, 8 frees, 2,230 bytes allocated
    ..
    

    发生了什么事?

    更新:创建一个线程而不是两个线程,不会显示内存泄漏。

1 个答案:

答案 0 :(得分:0)

您的问题的标题是错误的 - 您没有正确使用线程。但我不认为你的内存泄漏与任何未定义行为的实例有关。它只是一个虚假的"泄漏"由valgrind报告(假设您正在使用带有glibc的Linux系统)glibc内部。请参阅以下相关问题:

相关问题