从多个线程返回动态分配的char数组并在c中释放main内部的内存

时间:2021-03-03 16:20:36

标签: c multithreading memory-leaks dynamic-memory-allocation

我创建了一个线程数组,并根据 isSetFunc() 中的某些条件更改了全局变量。在返回动态分配的字符数组并在 main 中打印它时,它只在 main 函数中打印最后一个线程的结果,并且在释放线程内部创建的 main 函数内的内存时也没有被释放。

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER 10

int gset;
int gnot_set;

pthread_mutex_t glock;


void *SetFunc(void *args){
    char* string = (char *)calloc(BUFFER, sizeof(char));

    int* arg = (int *) args;

    pthread_mutex_lock(&glock);
    if(*arg < 4){
        gset++;
        strcpy(string, "True\n");
    }
    else{
        gnot_set++;
        strcpy(string, "False");
    }
    pthread_mutex_unlock(&glock);

    return string;
}


int main()
{

    int threadRes,
    i = 0;
    void* pResult;
    pthread_t* thread;

    pthread_mutex_init(&glock, NULL);

    thread = (pthread_t *)malloc(sizeof(pthread_t)*(10));

    while (i < 10)
    {
        threadRes = pthread_create(&(thread[i]), NULL, &isSetFunc, &i);
        if(threadRes != 0){
            fprintf(stderr, "Error occured while creating a thread\n");
            return -1;
        }
        pthread_join(thread[i], &pResult);
        i++;
    }

    printf("In main thread: %s\n", (char *)pResult);

    printf("\ng_set = %d\ngnot_set = %d\n", gset, gnot_set);
    pthread_mutex_destroy(&glock);

    free(thread);
    free(pResult);

    return 0;
}

输出

==387== Memcheck, a memory error detector
==387== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==387== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==387== Command: ./a.out
==387==
==387== error calling PR_SET_PTRACER, vgdb might block
In main thread: False

g_set = 4
gnot_set = 4
==387==
==387== HEAP SUMMARY:
==387==     in use at exit: 70 bytes in 7 blocks
==387==   total heap usage: 11 allocs, 4 frees, 4,512 bytes allocated
==387==
==387== LEAK SUMMARY:
==387==    definitely lost: 70 bytes in 7 blocks
==387==    indirectly lost: 0 bytes in 0 blocks
==387==      possibly lost: 0 bytes in 0 blocks
==387==    still reachable: 0 bytes in 0 blocks
==387==         suppressed: 0 bytes in 0 blocks
==387== Rerun with --leak-check=full to see details of leaked memory
==387==
==387== For lists of detected and suppressed errors, rerun with: -s
==387== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

任何帮助将不胜感激和感谢。

1 个答案:

答案 0 :(得分:1)

您的线程一次只运行一个,因此您只在所有线程运行后打印最终结果。

pthread_join 函数使调用线程等待指定线程返回。由于您在 pthread_join 之后立即调用 pthread_create,这意味着您创建一个线程,等待它完成,然后创建一个新线程,等等。

您看到的内存泄漏是因为每个线程都返回分配的内存,但您只在程序结束时释放它一次,因此您只释放了最后一个线程的结果。

您需要两个循环:一个用于创建线程,另一个用于连接它们。第二个循环应该调用 pthread_join,锁定互斥锁,打印值,解锁,然后 free 返回值。

相关问题