线程连接后,结构内的数组在 C 中被销毁

After thread join an array inside a struct was destroyed in C

我正在尝试使用 memcpy 将结构内的数组收集到全局范围内的数组。我检查了我的代码,我可以验证我分配给每个数组的大小是否正确且相同。我可以确认我的问题出在 mythrD.sample,但目前我没有发现任何问题。这是我的代码片段:

int main(int argc, char**argv) {
    int numbers = atoi(argv[1]);
    int ps = atoi(argv[2]);
    int i;
    thrD *mythrD = (thrD *) malloc(sizeof(thrD)*ps);
    for (i = 0; i < ps; i++)
    {
        mythrD[i].pid = i;
        mythrD[i].n = numbers;
        mythrD[i].ps = ps;
    }

    long int * array = (long int *) malloc(sizeof(long int)*numbers);
    long int * g_samples = (long int *) malloc(sizeof(long int)*(ps*ps));

    for (i = 0; i < numbers; i++)
    {
            array[i] = rand()%20;
    }

    for (i = 0; i < ps; i++)
    {
        data[i] = (long int*) malloc(sizeof(long int)*chunkSize);
        memcpy(data[i],&array[i*chunkSize], chunkSize*sizeof(long int));
        mythrD[i].chunk = data[i];
    }   

    for (i=0; i < ps; i++) {
        pthread_create(&ids[i], NULL, threadFn1, (void*)&(mythrD[i]));
    }

    pthread_barrier_wait(&mybarrier);

    for (i=0; i < ps; i++) {
        pthread_join(ids[i], NULL);
    }
    pthread_barrier_destroy(&mybarrier);

    for (i = 0; i < ps; i++)
    {
        for (int j = 0; j < ps; j++)
        {
            printf("%ld ",mythrD[i].sample[j]);
        }
    }

    for (i = 0; i < ps; i++) {
        memcpy(&g_samples[i*ps], mythrD[i].sample, ps*sizeof(long int));
    }

    for (i = 0; i< ps*ps; i++) {
        printf("%ld ",g_samples[i]);
    }
    return 0;
}

void* threadFn1(void * chunkD) {
    thrD mychunkD = *(thrD *) chunkD;
    int off_set = mychunkD.n/(mychunkD.ps*mychunkD.ps);
    int chunkSize = mychunkD.n/mychunkD.ps;
    pthread_barrier_wait(&mybarrier);
    mychunkD.sample = (long int *) malloc(sizeof(long int)*(chunkSize/off_set));
    for (int i = 0; i < chunkSize/off_set; i++)
    {
        mychunkD.sample[i] = mychunkD.chunk[i*off_set];
    }
    return NULL;
}

这是我定义的结构:

typedef struct threadData{
    long int *chunk;
    long int *sample;
    int pid;
    int n;
    int ps;
} thrD;

我想通了这个问题。我不应该分配threadFn中的内存,因为当我们离开线程时,那块内存就会丢失。如果我在 main 中分配 mythrD.sample,我应该能够在主范围内维护它。

所以应该是:

int main ()
{
    for(int i =0; i<ps; i++)
    {
        mythrD[i].sample = (long int *) malloc(sizeof(long int)*ps);   
    }
}