simon
simon

Reputation: 1145

Segfault when dereferencing pointer set by pthread_join

I have the following code for testing how to "implement return values" using pthread_exit() and pthread_join().

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

void* busy() {

    int returnValue = 2;
    pthread_exit((void*)&returnValue);

}


int main() {

    void* retVoidPtr = NULL;
    int* retValPtr = NULL;
    int retVal;

    pthread_t busyThread;
    pthread_create(&busyThread, NULL, busy, NULL);
    pthread_join(busyThread, &retVoidPtr);
    retValPtr = (int*) retVoidPtr;
    retVal = *retValPtr;

    printf("Busy thread returned %d\n", retVal);

    return 0;

}

The program compiles fine, but never gets to the printf statement. A segfault occurs at the line retVal = *retValPtr. Using gdb, I can see that the retValPtr pointer is no longer NULL but when I try print *retValPtr gdb says "Cannot access memory at address 0x...". Any suggestions where I'm going wrong?

Upvotes: 1

Views: 595

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

A C function can't return a pointer to a value on the stack under the best of circumstances. If that stack is the stack of a thread that has terminated, though, we're talking complete disaster, as the memory for that thread's stack may no longer be mapped -- that appears to be the case here.

Your thread function needs to return a pointer to data that will remain valid when the thread terminates: a global variable, or a block obtained from malloc().

Upvotes: 8

Related Questions