I got an error message of Segmentation fault (core dump) when I try to run this code.
Note: This is a really long program (almost 600 lines) so I only posted the ones that I ‘think’ is related. Let me know if more needed? 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 */
}
What you’re doing is:
check = pthread_create( &tid[i], NULL, tFunction,(void *) 4);And treating the 4th argument as an
int *, which it obviously isn’t. When you dereference the address 4 intFunctionyou get a segfault.If you want to pass a pointer to an
intwith a value of 4, pass the address of anintvariable, ie:EDIT:
pthread_joinis going to be useful so that you can wait for your threads to terminate before exiting your program.EDIT2: If you haven’t read the comments: You should ensure that if your passing a local variable (as with this example which was meant to show a very minor change to his code to get it working) that any new threads finish before the variable goes out of scope with the use of
pthread_join, or to dynamically allocate memory for the variable on the heap.