eral eral - 2 days ago 4
C++ Question

segmentation fault while using pthreads in class

I have the follwing code that gets core dumped error. Each C instance creates their own thread then runs. I guess there is something wrong with static function and class argument "count". When I comment out the code that prints it, no fault occurs..

#include <iostream>
#include <pthread.h>
using namespace std;

class C {
public:
int count;
C(int c_): count(c_){}
public:
void *hello(void)
{
std::cout << "Hello, world!" <<std::endl;
std::cout<<count; // bug here!!!
return 0;
}

static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}

void run() {

pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, NULL);
}

};

int main() {

C c(2);
c.run();

C c2(4);
c2.run();

while(true);

return 0;
}

Answer

Decided to write an answer. You were calling hello_helper with a context of NULL based on how you were creating your thread. C++ fully allows you to call member functions on null pointers, and no error occurs unless a member element is accessed.

In your case, by adding the line to print count. You are now accessing a member variable on a null pointer, which is a big no-no.

Here's an example of what you were getting away with:

#include <iostream>
class Rebel
{
    public:
    void speak()
    {
        std::cout << "I DO WHAT I WANT!" << std::endl;        
    }    
};
int main()
{
    void * bad_bad_ptr = NULL;
    ((Rebel*)bad_bad_ptr)->speak();
}

Output:

I DO WHAT I WANT!

By modifying your pthread_create call to pass the this pointer (i.e. pthread_create(&t, NULL, &C::hello_helper, this);, you now have a valid instance to access member variables on.

Comments