polslinux
polslinux

Reputation: 1779

How to pass malloced variable into a struct to a newly created struct in C

Let's take this example:

struct args{
    char *fname;
}

int main(void){
    struct args tArg;
    tArg.fname = malloc(10);
    strcpy(tArg.fname, "ciao");
    pthread_create(&p1, NULL, thread, (void *)&tArg);
    pthread_join(p1, NULL);
    free(tArg.fname);
    return 0;
}

void *thread(void *p1Arguments){
    struct args *p1 = p1Arguments;
    printf("%s\n", p1->fname);
}

the printf into the thread leads the program to a segfault because there is nothing into p1->fname.
What can i do to pass a malloc'ed string?

EDIT: i'm sorry i forgot to write the pthread_join

Upvotes: 3

Views: 89

Answers (5)

masoud
masoud

Reputation: 56499

You passed it correctly.

You free(tArg.fname);, But thread is trying to use tArg.fname.

// ...

pthread_create(&p1, NULL, thread, (void *)&tArg);

pthread_join(p1, NULL); // <-- PUT THIS AND GIVE A MOMENT TO THREAD

free(tArg.fname);

// ...

Upvotes: 1

rahul.deshmukhpatil
rahul.deshmukhpatil

Reputation: 997

It may be stack problem.

targ you have passed is created on stack. when you pass tArg address (which is on stack of main program), thread has its own stack section. I suggest you two solutions.

1> try by malloc tArg itself. declare it as pointer to struct. 2> or define tArg as global variable, which will force it to allocated on global data section and not stack section.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60017

The thought is

pthread_create(&p1, NULL, thread, (void *)&tArg);
free(tArg.fname);

is incorrect.

The thread should do the free bit.

And the main does a join

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25705

Other than waiting for the thread to complete, as stated by @Claudiu you must also cast the p1Arguments - this is one of the few places where a cast is necessary in C language.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121749

It looks like:

1) You're correctly allocating and initializing "fname" in struct tArg

2) You're also correctly passing tArg into your thread

... BUT ...

3) Your main program is deallocating "fname" before the thread accesses it (bad!)

SUGGESTION:

Put a "getchar()" after you create the thread (and BEFORE you call "free()"), so that main will wait for the user to hit "ENTER" before it frees and before it exits.

Upvotes: 1

Related Questions