Ken Ken - 1 month ago 6
C Question

Segmentation fault (core dumped) error when creating thread

I'm not sure how to debug this error since it can be caused by a lot of things. What I was able to do is comment out parts of the program and compiling it repeatedly in order to trace which part of the program produced the error, and I think this part produces the error:

Here I want to create a thread:

int j = 0; //not the actual value, just showing that j is of type int
pthread_create(&thread_id, NULL, strikeMultiples, (void*)j);


Maybe it could also be caused by the strikeMultiples function, which is invoked when the thread is created:

static void* strikeMultiples(void* prime) {
int * primej = (int *) prime;
int j = *primej;
free (prime);
int k;
for (k = 2; j * k <= NROF_SIEVE; k++) {
BIT_CLEAR(buffer[(j * k)/64], (j * k)%64);
}
return NULL;
}

Answer

The problem is that you pass an int to the function (casted to a void *) and then subsequently try to read it as an int *.

Also, you're attempting to free something that was not returned from malloc and family.

Pass the address of the int value, and don't free it in the function. Also, it's not necessary to cast between a void * and any non-function pointer.

static void* strikeMultiples(void* prime) {
    int *primej = prime;
    int j = *primej;
    int k;
    for (k = 2; j * k <= NROF_SIEVE; k++) {
        BIT_CLEAR(buffer[(j * k)/64], (j * k)%64);
    }
    return NULL;
}

...

pthread_create(&thread_id, NULL, strikeMultiples, &j);
Comments