Search code examples
ccharpthreadscoredump

Passing char* to pthread crashing


I am trying to get a time-based pooling system with threads. I managed to pull this off using fork(), now I am trying to implement it using threads. The timer thread seems to work fine, but for some reason I cannot pass a char* array to the thread (dumping core).

Note: If I try to exit the thread with status 0, I get no warning about giving an integer to a function returning void*. BUT, when I am trying to return something else, let it be 1, I get a warning. I tried to cast them to void*, but with no impact.

Now, for some code:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define COUNTING_SUCCESS 0
#define POOLING_SUCCESS 1

int size = 3;

void *count(void *bound_arg){
    int index = 0;
    int *bound = (int*)bound_arg;
    printf("Counting started...\n");
    while(index < *bound){
        printf("You have %d seconds left\n",*bound - index);
        sleep(1);
        index++;
    }

    printf("Time's up!\n");
    pthread_exit(COUNTING_SUCCESS);
}

void *pool(void *questions_ptr){
    char *questions = (char*)questions_ptr;
    char *answer = calloc(sizeof(char*)*size,size);
    for(int i =0 ; i < size ; i++){
        printf("%s : ",questions[i]);
        scanf("%s",&answer);
    }
    pthread_exit(0);

}

int main(){
    char* questions[] = {"Q1","Q2","Q3"};
    int limit = 3 ;
    int *countingLimit = &limit;
    void *countingStatus;
    void *poolingStatus;


    pthread_t timerThread;
    int threadID = pthread_create(&timerThread,NULL,count,(void*)countingLimit);
    pthread_join(timerThread,&countingStatus);
    printf("%d\n",(int*)countingStatus);

    pthread_t poolingThread;
    int poolingThreadID = pthread_create(&poolingThread,NULL,pool,(void*)questions);
    pthread_join(poolingThread,&poolingStatus);
    printf("%d\n",(int*)poolingStatus);



}

Sample output:

Counting started...
You have 3 seconds left
You have 2 seconds left
You have 1 seconds left
Time's up!
0
Segmentation fault (core dumped) //this is where i try to pass the char*

I cannot get it to enter the function.

P.S. I am building the executable using:

gcc -o pool pool.c -pthread

Solution

  • This has nothing to do with threads. You are passing a single char to printf where is it expecting a char * (for a string), so it crashes:

    printf("%s : ",questions[i]);
    

    you've declared quesstions as a char * (a single string), so you're fetching a single char that will then get treated as a bogus pointer by printf and crash.

    You probably intended to declare questions as char **, as that is what you are passing in as the pthread argument:

    char **questions = (char**)questions_ptr;