c prog that take int x and pass it to thread to return x+10
i tried to free()mem i allocate in prog using malloc
// problem i get this error Aborted (core dumped)

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *fun(void *TX);
int main()

{
int x =50;
void *exitstat;
pthread_t thread1;
pthread_create(&thread1, NULL, fun, &x);
pthread_join(thread1, &exitstat);
int *result=(int *)exitstat;
printf("%d",*result);
// problem is here i get this error  Aborted (core dumped)
//free(exitstat);
return 0;
}

void *fun(void *TX)
{
int *num = (int*)malloc(sizeof(int*)) ;
num=(int*)TX;
(*num)=(*num)+10;
//free(num); // can't free it here need to return num
return num;
}

note :
prog work fine (test on cygwin) if i remove free(exitstat);
but that lead to mem leak

Why are you freeing TX?

i tried to free()mem i allocate in prog using malloc

But you don't. You try to free the result of fun(), which is a pointer to int that corresponds to the address of x in main(). In other words, you're trying to free something that should not be freed. The problem is here:

// Memory is allocated to num, all is well
int *num = (int*)malloc(sizeof(int*));

// The memory allocated above is leaked away and now num points to TX,
// which is a pointer to x in main (*not* a pointer to dynamic memory)
num=(int*)TX;

At this point you already have a memory leak, and any attempt to free num or any reference to num will fail miserably because the pointer was not previously returned by malloc(), calloc(), or realloc().

Remove that second line as it's wholely unnecessary in the first place. What you probably wanted to do is this:

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

void *fun(void *TX)

int main(void)
{
    void *exitstat;
    pthread_t t;
    int x = 50;

    pthread_create(&t, NULL, fun, &x);
    pthread_join(t, &exitstat);

    printf("%d\n", *(int*)exitstat);
    free(exitstat);

    return 0;
}

void *fun(void *TX)
{
    int *num = malloc(sizeof *num);

    *num = *(int*)TX;
    *num += 10;

    return num;
}

Why are you freeing TX?

While correct, that's not informative.

commented: Respect! +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.