简体   繁体   中英

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?

AC 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM