简体   繁体   中英

pthread_create segmentation fault

I'm using the method 'pthread_create' in my program, and get a segmentation fault INSIDE THIS METHOD.
What can possibly cause this? I'm calling this function with the correct arguments' types!

this is the code:

pthread_t* _daemon;


void* writer(void* arg){
    // stuff that dont involve "arg"...
}


int initdevice(){
    if(pthread_create(_daemon, NULL, &writer, NULL) != 0) //seg in this line
    {

      cerr << "system error\n";
      return ERR_CODE;
    }
    return SUCCESS;
}

int main () {
    initdevice();
    return 0;
}  

Note: I've tried to run it also without the '&' before the calling to writer in pthread_create, and also - we've tried sending to this method some void* argument instead of the last NULL argument.

Your probelem is here:

pthread_t* _daemon;

This should be:

pthread_t  daemon;

Then change the call to pthread_create:

if(pthread_create(&daemon, NULL, &writer, NULL) != 0)

The idea is that pthread_create takes a pointer to an existing pthread_t object so that it can fill in the details. You can think of it as the C version of a constructor. Initially the pthread_t object is uninitialized this initializes it.

In addition your code is still probably not going to always work as you do not wait for the thread to finish. Make sure your main thread does not finish before all the children:

int main () 
{
    initdevice();
    pthread_join(daemon, NULL); // wait for the thread to exit first.
    return 0;
}  

you must allocate _daemon variable with new or malloc function, because you have use of a pointer . like bellow :

pthread_t* _daemon;
_daemon = new pthread_t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM