Alfred
Alfred

Reputation: 1673

Posix Pthread in C

I have the following questions regarding pthread of posix.

Regards

Upvotes: 1

Views: 197

Answers (2)

the_jk
the_jk

Reputation: 599

First of, you should never do (void**)&x as pointers off different types need not be of the same size.

Now, some scenarios (some valid, some working but invalid and some just broken):

Foo() returning a pointer to an int (valid):

void* Foo(void *arg)
{
    int *ret = malloc(sizeof(int));
    *ret = 42;
    return ret;
}

void *ptr;
int *x;
pthread_join(thread, &ptr);
x = ptr;
printf("%d", *x);
free(x);

Foo() returning an int (invalid but usually work):
Platforms where int is larger than a pointer this will not work.

void* Foo(void *arg)
{
   return 42;
}

void *ptr;
int x;
pthread_join(thread, &ptr);
printf("%d", (int)ptr);

Foo() returning a pointer to static int (invalid and never works): All static memory in Foo() is freed when Foo() returns, before pthread_join() can copy the value.

void* Foo(void *arg)
{
   int ret = 42;
   return &ret;
}

void *ptr;
int *x;
pthread_join(thread, &ptr);
x = ptr;
printf("%d", *x);

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78983

You shouldn't do that: at your level of understanding of C casts should be simply forbidden. If you learned that in a course, this is not really high quality.

First of all, &x is the address of a pointer so the result is int**, so well two indirections.

But casting that int away is dangerous, pointers to int and void don't have necessarily the same width on different platforms. So please do

void*x;
pthread_join(tid, &x);

printf("%d",*(int*)x);

Upvotes: 0

Related Questions