내 프로그램에서 세그 폴트가 발생했으며 그 원인이나 원인을 찾는 방법이 확실하지 않습니다. 어떤 도움이라도 대단히 감사하겠습니다!C에서 세그 폴트의 원인
코드에서 한 단어 씩 읽으려고 시도하지만 줄 번호를 추적해야합니다. 그런 다음 데이터가 단어와 줄 번호 인 연결된 목록을 만들려고합니다.
(두 개의 파일이 함께이 컴파일)
void main(int argc, char **argv){
file = fopen(argv[1],"r");
struct fileIndex *fIndex = NULL;
delimiters = " .,;:!-";/*strtok chars to seperate*/
int wCount = wordcount(file);/*number of words in file*/
char **str[wCount+1];/*where the lines are being stored*/
int j=0;
while(!feof(file)){/*inserting lines*/
fscanf(file, "%s", &str[j]);
j++;
}
char *token, *cp;
int i;
int len;
for(i = 0; str[i]; i++){/*checking to insert words*/
len = strlen(*str[i]);
cp = xerox(*str[i]);
token = strtok(cp, delimiters);
if(!present(fIndex, token)){
insert(fIndex, i+1,token);
}
while(token!=NULL){
token = strtok(NULL, delimiters);
if(!present(fIndex, token)){
insert(fIndex, i+1,token);
}
}
i++;
}
fclose(file);
}
int strcmpigncase(char *s1, char *s2){/*checks words*/
for(;*s1==*s2;s1++,s2++){
if(*s1=='\0')
return 0;
}
return tolower(*s2)-tolower(*s2);
}
present(struct fileIndex* fIndex, char *findIt){/*finds if word is in structure*/
struct fileIndex* current = fIndex;
while(current!=NULL){
current = current -> next;
if(strcmpigncase(current -> str, findIt)==0){
return current -> lineNum;
}
}
return 0;
}
void insert(struct fileIndex *head, int num, char *insert){/*inserts word into structure*/
struct fileIndex* node = malloc(sizeof(struct fileIndex));
node -> str = insert;
node -> lineNum = num;
node -> next = head;
head = node;
}
#define IN_WORD 1
#define OUT_WORD 0
int wordcount(FILE *input)/*number of words in file*/
{
FILE *open = input;
int cur; /* current character */
int lc=0; /* line count */
int state=OUT_WORD;
while ((cur=fgetc(open))!=EOF) {
if (cur=='\n')
lc++;
if (!isspace(cur) && state == OUT_WORD) {
state=IN_WORD;
}
else if (state==IN_WORD && isspace(cur)) {
state=OUT_WORD;
}
}
return lc;
}
char *xerox(char *s){
int i = strlen(s);
char *buffer = (char *)(malloc(i+1));
if(buffer == NULL)
return NULL;
char *t = buffer;
while(*s!='\0'){
*t=*s;
s++; t++;
}
*t = '\0';
return buffer;
}
코드를 들여 쓰고 코드를 문제가 있다고 생각되는 부분으로 줄이십시오. –
gdb를 사용하는 것이 좋습니다. 프로그램을 실행하면 segfault가 발견 될 때마다 "bt"를 입력하십시오. 스택이 표시됩니다. – eyalm
좋습니다. 모든 유능한 프로그래머는 궁극적으로 gdb와 같은 디버거를 사용하는 법을 배우기를 원할 것입니다. 차를 통과 할 수 있으며 사고의 줄 번호를 알려줍니다. 중단 점을 설정하고 값을 확인할 수도 있습니다. – hellork