Marià
Marià

Reputation: 263

error in mutex initialization with pthread

Hi guys i'm trying to start this mutex but the code doesn't work:

typedef struct{
        int somma;
        pthread_mutex_t mutex;  // TODO completare con le variabili per la sincronizzazione tra i thread
}Buffer;


typedef struct {
        int id;
        Buffer* b;
} parametri;

in the main i do :

parametri * p=malloc(sizeof(parametri));
        init_buffer(p->b);

and i call this function:

void init_buffer(Buffer* a){
       pthread_mutex_init(&a->mutex,NULL);      //TODO inizializzazione del buffer

        printf("[SERVER] -INIT...\n");
}

but the code stop work and doesn't print the [SERVER]INIT so i think it's a problem of mutex init.

Upvotes: 0

Views: 262

Answers (1)

dbush
dbush

Reputation: 223907

The pointer p->b in main is uninitialized. You then pass that uninitialized pointer to init_buffer and attempt to dereference it. Doing so triggers undefined behavior.

You can fix this by either allocating space for b:

parametri *p=malloc(sizeof(parametri));
p->b = malloc(sizeof(Buffer));

Or changing the struct definition to use an instance of Buffer instead of a pointer:

typedef struct {
        int id;
        Buffer b;
} parametri;

Upvotes: 1

Related Questions