Vladimir Berlev
Vladimir Berlev

Reputation: 502

Using pthreads and malloc

I asked a question Using sockets in multithread server yesterday. In this question I described segmentation fault under Solaris in multithreaded server. Now I have found the core of error and written code, that shortly demonstrates it:

#include <stdlib.h>
#include <pthread.h>


int main(int argc, char *argv[])
{
    pthread_attr_t *attr;

    attr = (pthread_attr_t *)malloc(sizeof(pthread_attr_t));
    pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

    malloc(0);
    malloc(0); //Segmentation fault there

    return 0;
}

Second malloc crashes with Segmentation fault. While this code executes normally:

#include <stdlib.h>
#include <pthread.h>


int main(int argc, char *argv[])
{
    pthread_attr_t *attr;

    attr = (pthread_attr_t *)malloc(sizeof(pthread_attr_t));
    // pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);

    malloc(0);
    malloc(0);

    return 0;
}

Could you please explain the reason of the error?

P.S.: I compile with gcc -pthreads -lpthread -D_REENTRANT keys.

Upvotes: 3

Views: 2694

Answers (1)

Michael Burr
Michael Burr

Reputation: 340316

From the docs on pthread_attr_setdetachstate():

The behavior is undefined if the value specified by the attr argument to pthread_attr_getdetachstate() or pthread_attr_setdetachstate() does not refer to an initialized thread attributes object.

It's possible that the pthread_attr_t object the attr argument points to contains a pointer to some state maintained by the pthreads library. If it hasn't been initialized, that pointer would be garbage so the pthread_attr_setdetachstate() call might corrupt the heap.

See the pthread_attr_init() function to see how to properly initialize the attributes object.

Upvotes: 4

Related Questions