Seg Fault with argument 4 pthread_create ()

When I tried to run this code, I received a Segmentation error message (core dump). Note. This is a really long program (almost 600 lines), so I published only those that I think are related. Let me know if necessary? Thanks in advance:)

#define CONSTANT 4 int main() { pthread_t tid[CONSTANT]; int i, check; for( i = 0; i < CONSTANT; i++ ) { check = pthread_create( &tid[i], NULL, tFunction, (void *) CONSTANT ); } } void * tFunction ( void * param ) { int num = * (int *) param; /* Seg fault line */ } 
+4
source share
2 answers

What are you doing:

check = pthread_create( &tid[i], NULL, tFunction, (void *) 4 );

And considering the 4th argument as int * , which obviously is not there. When you tFunction address 4 in tFunction , you get segfault.

If you want to pass a pointer to an int with a value of 4, pass the address of the int variable, that is:

 #include <pthread.h> #define CONSTANT 4 void * tFunction ( void * param ) { int num = * (int *) param; /* Seg fault line */ } int main(void) { int arg = CONSTANT; pthread_t tid[CONSTANT]; int i, check; for( i = 0; i < CONSTANT; i++ ) { check = pthread_create( &tid[i], NULL, tFunction, (void *) &arg ); } return 0; } 

EDIT : pthread_join will be useful, so you can wait for your threads to finish before exiting your program.

EDIT2 . If you haven’t read the comments yet: you must make sure that if your transfer is a local variable (as in this example, which had to show very minor changes in its code in order to get it working), that any new threads end before the variable goes out of scope using pthread_join or dynamically allocates memory for a variable on the heap.

+2
source

If you are going to specify a constant in void * and pass it as a context parameter, you need to perform an additional operation on the other end:

 int num = (intptr_t)param; 

Must do it for you. Your current program has an extra draw, which ultimately does something like this:

 int num = *(int *)4; 

and that your program crashes right now.

+3
source

All Articles