Search code examples
cmemory-managementmemory-leakspthread-join

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


I'm trying to use memcpy to gather an array inside a struct to an array in the global scope. I checked my code, and I can verify that the size I allocate to each array is correct and identical. I can confirm that my problem is with mythrD.sample,but I didn't see anything wrong at this moment. Here is my code snippet:

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

And here is the struct that I defined:

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

Solution

  • I figured out this problem. I shouldn't allocated the memory in the threadFn, because when we left the thread, that memory will lost. If I allocate mythrD.sample in main, I should be able to maintain that on main scope.

    so it should be:

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