Dereference pointers from threads

Viewed 65

How would I deference my argument to get the integer value in my print statement and also free the pointer inside the function?

This is a simpler version of what I'm running into with a project I'm working on:

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


void* my_Func(void *received_intPointer){
    int val = *(int*) received_intPointer;
    printf("value: %d \n", val);
    free(received_intPointer);
    
}
int main(){
    int array[5];
    int *ptr[5];
   
   for(int i=0; i<5; i++){
        ptr[i] = (int*) malloc(sizeof(int));
    }
    
    printf("\nEnter 5 numbers:\n");
    for (int i=0; i<5; i++){
        scanf("%d", &array[i]);
        ptr[i] = &array[i];
    }
    pthread_t tid[5];
    for(int i=0; i<5; i++){
        pthread_create(&(tid[i]), NULL, my_Func, &ptr[i]);
    }
    for (int i=0; i<5; i++){    
        pthread_join(tid[i], NULL);
    }
}

1 Answers

Two bugs here:

  • my_Func is expecting its argument to be a pointer to the int that it should print (where that pointer has been cast to void *). ptr[i] is supposed to be that pointer. But you are passing &ptr[i] which is a pointer to that pointer. In other words, your function is really expecting int * but you pass it int **. So it should be:
        pthread_create(&(tid[i]), NULL, my_Func, ptr[i]);
  • ptr[i] = &array[i]; overwrites the pointer ptr[i] with a pointer to the int array[i]. So ptr[i] is no longer the pointer you received from malloc. You have leaked that memory, and what is worse, my_Func will attempt to free &array[i] which is not malloc'ed.

    I think you wanted to copy the int from array[i] into the space you malloced previously, so this line should be *ptr[i] = array[i];.

Related