Question

I am trying to allocate memory dynamically for the arg_struct. If I just allocate it on the stack it works correctly, but not dynamically. Dynamically it prints the string in the main function but when it is passed to the thread function it doesn't work. Any ideas as to why it doesn't work?

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


struct arg_struct {
    int *arg1;
    char *str;
};

void *print_the_arguments(void *arguments)
{
    struct arg_struct *args = (struct arg_struct *)arguments;
    printf("The result is : %s\n",args->str);
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    pthread_t some_thread;
    struct arg_struct *args = malloc(sizeof(struct arg_struct));
    //struct arg_struct args; // uncommenting this and args.str WORKS (prints to thread function)
    args->str = malloc(sizeof(char)*6);
    args->str = "hello";
    //args.str = "hello";
    printf("printing from main: %s\n", args->str); // Prints here but not in other function

    if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
        printf("Uh-oh!\n");
        return -1;
    }

    return pthread_join(some_thread, NULL); /* Wait until thread is finished */

}
Was it helpful?

Solution

This

29     if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {

should be

29     if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)args) != 0) {

when you are dynamically allocating args. Also, I'd advise

 25     args->str = strdup("hello");

and skip the malloc.

This code:

 24     args->str = malloc(sizeof(char)*5);
 25     args->str = "hello";

results in a memory leak, the memory from malloc is leaked. Perhaps you meant

 24     args->str = malloc(sizeof(char)*5);
 25     strcpy(args->str, "hello");

but that is also incorrect. The 5 should be a 6 to account for the null character at the end of the string. strdup() is a good shortcut for malloc followed by strcpy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top