6

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.

Martin York
  • 257,169
  • 86
  • 333
  • 562
Zach
  • 537
  • 4
  • 9
  • 19
  • 4
    post the code you use around that call, you're probably not doing it right. – Mat Apr 03 '11 at 16:53
  • I think the problem is at line number 17. – Nawaz Apr 03 '11 at 16:55
  • 1
    Don't use underscore '_' as the first character of a global variable (Just don't use them at the beginning of variables). [These identifiers are reserved for the compiler and the OS](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797). – Martin York Apr 03 '11 at 17:22

2 Answers2

19

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;
}  
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 3
    @Nissim: Because your way is wrong! You are passing an initialized pointer (so it could point at anything) to a function that write via the pointer (thus writing anywhere in memory). – Martin York Apr 03 '11 at 17:20
1

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;