HotShot51015 HotShot51015 - 1 month ago 4
C Question

How to tell what is causing seg fault when using pthread_create?

I'm having trouble finding the cause of this seg fault when calling pthread_create...

GDB is giving me

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bc741d in pthread_create@@GLIBC_2.2.5 () from /lib64/libpthread.so.0


I'll include the part of the code that calls it and the part of the code which includes the function the threads are calling.

int main(int argc, char **argv)
{
/*
* Declare local variables
*/
int i, j; // LK
pthread_t *cat[NUM_CATS]; // LK
pthread_t *lizard[NUM_LIZARDS]; // LK


/*
* Check for the debugging flag (-d)
*/
debug = 0;
if (argc > 1)
if (strncmp(argv[1], "-d", 2) == 0)
debug = 1;


/*
* Initialize variables
*/
numCrossingSago2MonkeyGrass = 0;
numCrossingMonkeyGrass2Sago = 0;
running = 1;


/*
* Initialize random number generator
*/
srandom( (unsigned int)time(NULL) );


/*
* Initialize locks and/or semaphores
*/

sem_init(&driveway, 0, 20); // LK

/*
* Create NUM_LIZARDS lizard threads
*/

// LK
for(i = 0; i < NUM_LIZARDS; i++) {
pthread_create(lizard[i], NULL, lizardThread, (void *)(&i));
}


And the function called by pthread_create...

void * lizardThread( void * param )
{
int num = *(int*)param;

if (debug)
{
printf("[%2d] lizard is alive\n", num);
fflush(stdout);
}

while(running)
{

lizard_sleep(num); // LK
sago_2_monkeyGrass_is_safe(num); // LK
cross_sago_2_monkeyGrass(num); // LK
lizard_eat(num); // LK
monkeyGrass_2_sago_is_safe(num); // LK
cross_monkeyGrass_2_sago(num); // LK

}

pthread_exit(NULL);
}

usr usr
Answer

The segfault is very likely because of passing uninitialized thread ID to pthread_create(). The array lizard isn't initialized.

Instead use an array:

  pthread_t lizard[NUM_LIZARDS]; // LK

  ...

  // LK
  for(i = 0; i < NUM_LIZARDS; i++) {
    pthread_create(&lizard[i], NULL, lizardThread, (void *)(&i));
  }

Also, note that there's data race since you pass &i to all threads. Instead you can use an array to fix the data race.

  int arr[NUM_LIZARDS];
  for(i = 0; i < NUM_LIZARDS; i++) {
    arr[i] = i;
    pthread_create(&lizard[i], NULL, lizardThread, &arr[i]);
  }
Comments