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

在c中,从多个线程返回动态分配的char数组并释放main中的内存,c,multithreading,memory-leaks,dynamic-memory-allocation,C,Multithreading,Memory Leaks,Dynamic Memory Allocation,我已经创建了一个线程数组,并根据isSetFunc()中的某些条件更改了全局变量。当返回动态分配的字符数组并在主函数中打印它时,它只在主函数中打印最后一个线程结果,并且在主函数中释放内存时,在线程中创建的内存没有被释放 #include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h> #define BUFFER 10 int gset; int gn

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

#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;
}

非常感谢您的帮助。

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

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

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


您需要两个循环:一个用于创建线程,另一个用于连接线程。第二个循环应该调用
pthread\u join
,锁定mutux,打印值,解锁,然后
free
返回值。

执行此操作后,在Valgrind上运行代码时也会丢失一些字节。