Memory allocated on the stack for a different thread

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 ?

Reply to
Bogdan
Loading thread data ...

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 ?

Reply to
Bogdan

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

Reply to
jack

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.