#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.js 中获得了正确的大小。但是在调用第二个文件期间,我遇到了分段错误。使用 gdb,我了解到“**size[1] 和 **size[2] 尽管 malloc 为 NULL。但是在 main 开始时,我在分配内存时没有收到错误消息。这应该意味着内存是最初分配的。请帮助我该怎么办。