almariva
almariva

Reputation: 3

Global variable pointer in a thread

I can not use my global variable pointer buffer1 in a thread. Give me Segmentation fault. Why? Thank you.

# include <stdio.h>
# include <stdlib.h>
# include <pthread.h>
# include <malloc.h>
# include <semaphore.h>

int **buffer1;


int **crear_buffer(int tamano) {

    int i;
    int **matriz = (int **)malloc(sizeof(int *) * tamano);

    for (i = 0; i < tamano; i++) {
        matriz[i] = (int *)malloc(sizeof(int) * 2);
    }

    return matriz;
}

void *productor(void *arg){

    int num_pares= *((int *) arg);

    int i=0;
    int cont=0;

    while(cont<num_pares){

    int primero=5;
    int segundo=8;

    if (primero<=segundo){
        buffer1[i][0]=primero;
        buffer1[i][1]=segundo;
    }
    else{
        buffer1[i][0]=segundo;
        buffer1[i][1]=primero;

    }

    i=(i+1)%tamano_buffer1;
    cont++;

    }

    pthread_exit(NULL);

}


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

    sscanf(argv[1], "%d", &tamano_buffer1);
    sscanf(argv[2], "%d", &N);

    int **buffer1=crear_buffer(tamano_buffer1);

    pthread_t tid_productor;

    pthread_create(&tid_productor, NULL, productor,(void *) &N);

    pthread_join(tid_productor, NULL); 
    return 0;
}

Upvotes: 0

Views: 107

Answers (1)

nvoigt
nvoigt

Reputation: 77354

Because you never assigned it:

This is a NEW local variable named buffer1:

int **buffer1=crear_buffer(tamano_buffer1);

This would have been assigning to your existing global variable:

buffer1=crear_buffer(tamano_buffer1);

Upvotes: 2

Related Questions