如何处理动态分配结构C中的分段错误

如何处理动态分配结构C中的分段错误,c,file,struct,segmentation-fault,C,File,Struct,Segmentation Fault,我写了一个程序,从文本文件中读取单词。每行有一个单词。我需要找出每个单词重复多少次。到目前为止,为了找出这个问题,我从文件中读入了单词,并将它们全部放在动态分配的struct数组中。我的问题是,每当我试图运行程序时,它总是出现分段错误。我假设如何动态分配数据存在问题。 代码如下: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> //struc

我写了一个程序,从文本文件中读取单词。每行有一个单词。我需要找出每个单词重复多少次。到目前为止,为了找出这个问题,我从文件中读入了单词,并将它们全部放在动态分配的struct数组中。我的问题是,每当我试图运行程序时,它总是出现分段错误。我假设如何动态分配数据存在问题。 代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

//struct
struct _data {
    char *word;
    int number;
};


//scan for size of file
int SCAN(FILE *data) {
    int size = 0;
    char  s_temp[50];
    while (1) {
        fscanf(data, "%s", s_temp);
        if (feof(data)) break;
        size++;
   }
   return size;
}
//load content into struct
int LOAD(FILE *data, int size, struct _data *Wordstruct){
    int i;
    char temp[50];
    for (i=0; i <size; i++){
        fscanf(data, "%s", temp , &Wordstruct[i].word, &Wordstruct[i].number);
        Wordstruct[i].word =calloc(strlen(temp), sizeof(char));
        strcpy(Wordstruct[i].word, temp);
        if(strcasecmp(Wordstruct[i].word, temp) ==0){
            Wordstruct[i].number++;
        }

    }
    return size;
}
//count how many times each word repeats
void COUNT(struct _data *Wordstruct, int size){
    int i;
    int count;
    count =0;
    char *word;
    if (strcasecmp(Wordstruct[i].word, word)==0){
            count++;
            for(i=0; i<size; i++){
            printf("%s\n",Wordstruct[i].word,"occurs:\t",count);
            }
        }
    }
//main routine
int main(int argc, char *argv[]){
    int size;
    FILE *data;
    struct _data *Wordlist;
        if(argc <2){
            printf("Not enough arguments\n");
        }
        else{
            FILE *data= fopen(argv[1],"r");
            size =SCAN(data);
            LOAD(data, size, Wordlist);
            COUNT(Wordlist, size);
        }
return 0;
}
#包括
#包括
#包括
#包括
//结构
结构数据{
字符*字;
整数;
};
//扫描文件大小
整数扫描(文件*数据){
int size=0;
煤焦温度[50];
而(1){
fscanf(数据,“%s”,s_temp);
如果(feof(数据))中断;
大小++;
}
返回大小;
}
//将内容加载到结构中
整数加载(文件*数据,整数大小,结构_数据*字结构){
int i;
煤焦温度[50];

对于(i=0;i您尚未为
Wordlist
分配内存。添加

Wordlist = malloc(size*sizeof(*Wordlist));
在调用
LOAD
之前

正如@BLUEPIXY在评论中指出的那样,改变

Wordstruct[i].word =calloc(strlen(temp), sizeof(char));

更改此项:

Wordstruct[i].word =calloc(strlen(temp), sizeof(char));
Wordstruct[i].word =calloc(strlen(temp)+1, sizeof(char));
此:

Wordstruct[i].word =calloc(strlen(temp), sizeof(char));
Wordstruct[i].word =calloc(strlen(temp)+1, sizeof(char));
您需要考虑空终止符,
strlen()
在这里不为您这样做。

1)
Wordlist
未分配。2)
calloc(strlen(temp),sizeof(char));
allocate size need
strlen(temp)+1
3)
stracecmp(Wordstruct[i]。word,word)
word
未初始化。