#include<pthread.h>
#include<stdio.h>
#include<sys/stat.h>
#include<errno.h>
#define SIZE 3
/***I'm trying to send name of each file in a thread and trying to receive their respective size in main *******/
void *doit(void *name)
{
int *size;
struct stat st;
char temp_name[30];
memset(temp_name, '\0', sizeof(temp_name));
strcpy(temp_name, (char *)name); //type casted
stat(temp_name, &st);
*size = st.st_size; //calculated the size
printf("File name is: %s\n", temp_name);
printf("File size is: %d\n", *size);
pthread_exit((void *)size); //exited from thread
}
int main(int argc, char *argv[])
{
pthread_t th_id[SIZE];
int ret_val;
int i;
void **size[SIZE];
for(i=0; i<SIZE;i++)
{
size[i] = (void **)malloc(30*sizeof(void *)); //allocated memory to void double pointer
if(size[i] == NULL)
{
printf("Memory not allocated to %dth member of size\n", (i+1));
}
}
for(i=0; i<3; i++)
{
/*****Creating Thread**********/
ret_val = pthread_create(&th_id[i], NULL, &doit, (void *)argv[1+i]);
if(ret_val != 0)
{
perror("Thread creation error\n");
exit(0);
}
pthread_join(th_id[i], size[i]);
printf("Size is %d\n",**(int **)size[i]); //typecasted and printed
}
pthread_exit(NULL);
return 0;
}
In this program i'm getting segmentation fault after first call at pthread_join. when passing first file, i'm getting the proper size in main. but during call to second file i'm getting segmentation fault. With gdb i'm getting that the "**size[1] and **size[2] are getting NULL despite malloc. but in the start of main, i'm not getting error message while assigning memory. It should mean that the memory is assigned initially. Please help me what should i do.