0

我正在尝试执行一项分配,其中我将使用多个线程对文件中的输入进行排序,但是当我尝试使用结构数组来存储我需要在线程之后恢复的信息时,我遇到了分段错误。根据我的消息来源,我不确定它为什么会导致故障。

这是主文件,Threads.c seg 错误在 for 循环中,导致的行由注释指定。排序方法是我没有使用的另一个功能

#include "threads.h"
Threads* threadArray[4];
int linesPerThread;
int extraLines;

main(int argc, char *argv[]){
 int n;

 if( argc != 4){
  printf("Wrong Number of Arguements!\n");
  return;
}
  n = atoi(argv[1]);
 char *inName = argv[2];



*threadArray = (Threads*) (*threadArray, n*sizeof(Threads));  




FILE* file = fopen(inName, "r");
 if(!file){
printf("invalid file Name \n");
return;}

int lines = 0;
char xyz[5000]; //makes fgets happy
while(fgets(xyz, 5000, file) != NULL){
  lines = lines+1;
}
fclose(file);
linesPerThread = lines / n;


 extraLines = lines - linesPerThread;

 int i =0;
 int methodCounter =1;


 printf("Right before Loop \n \n");

 for(i; i < n; i++){

   printf("first part of loop \n");
 \\The ling below here Seg Faults.
   (*threadArray + i)->id = i;

   printf("right after first ThreadArray access \n");
   if(methodCounter < 3){
 printf("method counter 1\n");
(*threadArray+i)->methodID = methodCounter;
 methodCounter++;
   }else{
 printf("method counter condition 2 \n");
(*threadArray + i)->methodID = 3;
   methodCounter = 1;}
   if(extraLines > 0){
 printf("extra Lines condition 1 \n");
(*threadArray+i)->lines = linesPerThread +1;
 extraLines= extraLines -1;
   }else{
 printf("extraLines condition 2 \n");
 (*threadArray+i)->lines = linesPerThread;
   }
   printf("Right before Thread Creation \n \n");
   pthread_t tID;
   pthread_create(&tID, NULL, sortMethod, (void*) &((*threadArray+i)->id));
   (*threadArray+i)->threadID = tID;
   printf("right after thread creation \n \n");
 }
 printf("right after loop \n \n");
 int c=0;

 printf("before thread joining \n");
 for(c; c< n; c++){
   pthread_join( (*threadArray+ c)->threadID, NULL);
 }


 }

这是头文件,Threads.h

#include <sys/time.h>
#include <stdio.h> 
#include <pthread.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
  int id;
  int lines;
  pthread_t threadID;
  int methodID;
}Threads;

void* sortMethod(void*ptr);
int main(int argc, char *argv[]);

您能提供的任何帮助将不胜感激。

4

1 回答 1

0

在行

*threadArray = (Threads*) (*threadArray, n*sizeof(Threads));  

你设置threadArray[0](Threads*)(n*sizeof(Threads). 您可能想要 arealloc或 acalloc在该行中。

就目前而言,

(*threadArray, n*sizeof(Threads))

是一个逗号表达式,并且该逗号表达式的值被强制转换为Threads*.

由于您从未将内存分配给 的任何元素threadArray

(*threadArray + i)->id = i;

取消引用无效的指针。由于数组是静态的,因此指针最初初始化为空指针,您只需设置threadArray[0]为不同的值(但这也很可能也不指向有效内存)。

于 2013-01-02T23:41:18.593 回答