2013-01-02 45 views
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[]); 

,你可以提供任何幫助將不勝感激。

+0

如果你的陣列可以由多個線程訪問,你應該使用互斥保護它(或信號): 請看一看在這個崗位提出的解決方案: http://stackoverflow.com/questions/ 3144349/boost-threads-mutex-array –

回答

0

在行

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

要設置threadArray[0](Threads*)(n*sizeof(Threads)。您可能需要該行中的realloccalloc

既然這樣,

(*threadArray, n*sizeof(Threads)) 

是逗號表達,而逗號表達式的值被轉換爲Threads*

因爲你永遠不分配的內存中的任何threadArray元素,

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

解引用無效指針。由於數組是靜態的,所以指針最初被初始化爲空指針,你只能將threadArray[0]設置爲一個不同的值(但它並不指向有效的內存)。

+0

D'oh!我忘了打電話給realloc。我感覺很傻。非常感謝你,我永遠不會發現它。 –

+0

現在你已經明白了,[不要施加'malloc'](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – Joe