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 ?