user3142443 user3142443 - 2 months ago 19
C Question

segmentation fault from threads

I have written the code below but when I run it it brings segmentation fault. It compiles correctly though. Where are my mistakes?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
int *i = (int *) arg;
char buf[123];
snprintf(buf, sizeof(buf), "thread %d", *i);
return buf;
}

int main(int argc, char *argv[]) {
int i;
pthread_t *pt = NULL;
for (i = 0; i < N; i++) {
pthread_create(pt, NULL, run, &i);
}
return EXIT_SUCCESS;
}


Any hint is welcomed.

Thank you

usr usr
Answer

You have serveral issues:

1) You are passing a NULL to pthread_create() which is probably the reason for segfault.

2) You don't wait for the threads to complete (when main thread exits the whole process dies).

3) You are passing the address same variable i to all threads. This is a data race.

4) You are returning the address of a local variable buf from the thread function.

You can fix it like:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
  int *i = (int *) arg;
  char *buf = malloc(16);
  snprintf(buf, 16, "thread %d", *i);
  return buf;
}

int main(int argc, char *argv[]) {
  int i;
  void *ret;
  int arr[N];
  pthread_t pt[N];

  for (i = 0; i < N; i++) {
    arr[i] = i;
    pthread_create(&pt[i], NULL, run, &arr[i]);
  }

  for (i = 0; i < N; i++) {
    pthread_join(pt[i], &ret);
    printf("Thread %d returned: %s\n", i, (char*)ret);
    free(ret);
  }
  return EXIT_SUCCESS;
}

Note that you don't need to use pthread_join() calls. You can also cal pthread_exit() from the main thread so that only the main thread exit and other threads continue.