Search code examples
cmemory-managementpthreadsfree

How to free memory allocated by thread-function in the main


I have allocated heap memory in the thread function f1, this storage is used to calculate the value in the heap region so that the main function can see it.

Here is the thread function definition:

void *f1(void *input){


        int sum = (int*)malloc(sizeof(int));
        /* Do calculation */   
        pthread_exit((void*)&sum);
}

In the above code, the sum is the heap allocated storage, whose address is passed as a return value to the sum1 in the main().

I join the thread in the main() like this:

void *sum1;
pthread_join(tid1,(void**)&sum1);

Once i retrieved the value, i want to free the allocated memory. When i use free in the main, it complains like munmap_chunk(): invalid pointer

How can i explicitly and safely free this memory ?


Solution

  • You should send back the pointer, not its address

    pthread_exit(sum);
    ...
    pthread_join(tid1, &sum1);
    

    From the thread function you want to send back (with return or pthread_exit()) a pointer.
    At pthread_join() you want to obtain this pointer but the result of pthread_join() is an integer to report success/failure.
    Then we have to declare a pointer variable (sum1 here) to store the expected result and provide pthread_join() with the address of this variable so that it could be updated (the same way we provide addresses to scanf() in order to update the extracted variables).