#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;
}
在这个程序中,我在第一次调用pthread_join后出现分段错误。当传递第一个文件时,我在main中获得了合适的大小。但在调用第二个文件时,我遇到了分段错误。使用gdb我得到的是“** size [1]和** size [2]尽管是malloc但仍然为NULL。但是在main的开头,我在分配内存时没有收到错误信息。它应该意味着记忆最初分配。请帮我解决。
答案 0 :(得分:1)
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
您正在取消引用未经初始化的指针。你永远不会让size
指向任何东西。