如何处理动态分配的struct C中的Segmentation fault

时间:2015-03-09 20:58:45

标签: c file struct segmentation-fault

我编写了一个程序,用于从文本文件中读取单词。每行有一个单词。我需要找出每个单词重复多少次。到目前为止,为了找到这个,我已经从文件中读取了单词并将它们全部放在动态分配的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;
}

2 个答案:

答案 0 :(得分:0)

您还没有为Wordlist分配内存。添加

Wordlist = malloc(size*sizeof(*Wordlist));
在致电LOAD之前

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

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

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

答案 1 :(得分:0)

更改

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

这个:

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

您需要考虑NULL终止符,strlen()在这里不会为您执行此操作。