Home > Back-end >  pthread_ create in c generates segmentation fault
pthread_ create in c generates segmentation fault

Time:12-07

My teacher put this code on his slides and let us try to run it, but when i run i get "segmentation fault" errror. After some debugging I found out that the source of error is the function pthread_create(), if I pass the &attr parameter it gives me error but if I pass NULL everything works fine.
I fully understand what this code should do but i don't get why it gives error.

#include <pthread.h> 
#include<unistd.h> //threadAttr.c
void *my_fun(void *param){
    printf("This is a thread that received %d\n", *(int *)param);
    return (void*)3;
}
void main(){
    pthread_t t_id; pthread_attr_t attr;
    int arg=10, detachSTate;
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); //Set detached
    pthread_attr_getdetachstate(&attr,&detachSTate); //Get detach state
    if(detachSTate == PTHREAD_CREATE_DETACHED) 
        printf("Detached\n"); 
    pthread_create(&t_id, &attr, my_fun, (void *)&arg);
    
    printf("Executed thread with id %ld\n",t_id);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); //Inneffective
    perror("");
    sleep(3);
    int esito = pthread_join(t_id, (void **)&detachSTate); 
    printf("Esito '%d' is different 0\n", esito);
}

CodePudding user response:

Issues:

  1. void main() is (generally) an invalid form. It's int main().
  2. The code did not call pthread_attr_init.
    • This looks like the reason for segmentation fault - the values in attr are uninitialized, which causes pthread_create to act strangely.
  3. The code passed a pointer to an int where a pointer to void* is expected in pthread_join.
  4. The code did not #include <stdio.h> and #include <errno.h>
  •  Tags:  
  • c
  • Related