I am learning about function pointers and thread in C. The following code will create a thread that will read string from user. Then It will print the name which was entered by user on main thread. But I got Segmentation fault: 11
#include<pthread.h>
#include<stdio.h>
int agelimit;
char *string1, *string2;
void *getName();
//void (*getAge)();
main(){
pthread_t thread1,thread2;
string1 = malloc(1000);
//scanf("%s",string0);
pthread_create(&thread1, 0, getName, 0);
//pthread_create(&thread2, 0, getAge, 0);
sleep(10);
printf("name is %s age is",string1);
}
void *getName(){
int x;
printf("enter name:");
scanf("%s",&string1);
}
Though your code needs some more improvement/error handling but it seems you need to change the
to
to get it working now.
Pl. refer the Link for a good tutorial on
POSIX Threads Programming
Explanation:
string1 is a variable and stored in memory. So it is having a memory address say a1 (this is the starting address).
Now what is stored in this memory address? This comes from your assignment statement below.
malloc ->allocates a chunk of 1000 bytes of memory and returns the starting address of the chunk, which is say p1.
So now content of the variable string1 is p1 or in other words the memory cell a1 is now having p1(actually this should not be a single cell but a 4byte/8byte quantity..but I am assuming a single cell for simplicity).
Now what scanf expects as its 2nd argument here?
So when you are giving &string1 as an argument to scanf, you were passing a1 to scanf ,which is not correct. It should get p1 to work properly, so you need to pass string1 and not &string1
Hope this explanation helps. In general Pl. refer the c-faq link below, which is very helpful for understanding c concepts
comp.lang.c Frequently Asked Questions