What would get printed in the following C code and why?
void *helper(void *arg){
char *message = (char *) arg;
strcpy(message, “I am the child”);
return NULL;
}
int main(){
char *message = malloc(100);
strcpy(message, “I am the parent”);
pthread_t thread;
pthread_create(&thread, NULL, &helper, message);
pthread_join(thread, NULL);
printf(“%sn”, message);
return 0;
}
Expert Answer
Output:
I am the child
Here is code with explaination:
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
void *helper(void *arg){
char *message = (char *) arg;
strcpy(message, “I am the child”); // message variable assign “I am the child”
return NULL;
}
int main(){
char *message = malloc(100);
strcpy(message, “I am the parent”); // message variable has “I am the parent”
pthread_t thread; // thread variable
pthread_create(&thread, NULL, &helper, message); // created thread assigning the function helper function
pthread_join(thread, NULL); // invoke the function helper
printf(“%sn”, message); // prints the message
return 0;
}