Memory allocated on the stack for a different thread

Oct 25, 2010 2 Replies

Hi



I would like to test my understanding of threads. In the snipped below:



void* thread_starter(void *arg) { if (arg) { printf("arg = %d", *((int*)arg)); free(arg); } else { printf("null ptr"); } return NULL; }



int main(void) { pthread_t tid; int *pData = malloc(sizeof(*pData));



if (NULL == pData) { perror("malloc"); return EXIT_FAILURE; } *pData = 123;



if (0 != pthread_create(&tid, NULL, thread_starter, pData)) { perror("pthread_create"); return EXIT_FAILURE; } /*if (0 != pthread_join(tid, NULL)) { perror("pthread_join"); return EXIT_FAILURE; }*/ return EXIT_SUCCESS; }



If I don't wait to join the secondary thread, nothing is displayed. From my understanding, the pData pointer allocated on the main thread stack is deleted before being copied into the stack of the second thread, thus the correct address of the allocated heap memory cannot be retrieved. Am I right or wrong ?


Hi

I would like to test my understanding of threads. In the snipped below:

void* thread_starter(void *arg) { if (arg) { printf("arg = %d", *((int*)arg)); free(arg); } else { printf("null ptr"); } return NULL; }

int main(void) { pthread_t tid; int *pData = malloc(sizeof(*pData));

if (NULL == pData) { perror("malloc"); return EXIT_FAILURE; } *pData = 123;

if (0 != pthread_create(&tid, NULL, thread_starter, pData)) { perror("pthread_create"); return EXIT_FAILURE; } /*if (0 != pthread_join(tid, NULL)) { perror("pthread_join"); return EXIT_FAILURE; }*/ return EXIT_SUCCESS; }

If I don't wait to join the secondary thread, nothing is displayed. From my understanding, the pData pointer allocated on the main thread stack is deleted before being copied into the stack of the second thread, thus the correct address of the allocated heap memory cannot be retrieved. Am I right or wrong ?

I'd say the main thread falls through, and calls _exit() before the second thread has a chance to print anything. Doesn't matter if it prints something dependent on what is on the stack or if it calls printf("Hello world\n"), it is terminated when the main process exits and takes all its subthreads with it.

-J

Join the Discussion

Have something to add? Share your thoughts — no account required.

Didn't find your answer?

Ask the community — no account required