为什么会导致分段错误? (C 语言程序,用于计算文件中某个单词的出现次数)

问题描述 投票:0回答:1

countSH
根据行的第一个字符计算文件中单词出现的次数。

我还有一个获取用户输入的函数。

我分别编写了它们,当我单独测试这些功能时,它们都工作得很好。

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

int *countSH(char *filename, char *SentWord) {
    //opening file and checking whether it opens
    FILE *file = fopen(filename, "r");

    if (file == NULL) {
        perror("error while opening file");
        return NULL;
    }

    char line[500]; //line lenght = 500
    int hams = 0;
    int spams = 0;
    char *token = NULL;
    const char *word = SentWord;
    char *lineDupe;

    while(1) {
        if (feof(file)) { 
            break; //breaking the loop when getting to the end of the file
        } 

        if (fgets(line, sizeof(line), file) != NULL) { //if line != NULL
            lineDupe = strdup(line);
            token = strtok(lineDupe, " \t\n");
            while (token != NULL) {
                if (strcmp(token, word) == 0) {
                    if (line[0] == 'h') { //if line starts with h (ham)
                        hams++;
                    } else { //else it starts with s (spam)
                        spams = spams + 1;
                    }
                }
                token = strtok(NULL, " \t\n");
            }
        }
    }

    int countsh[2] = { hams, spams };

    if (hams == 0 && spams == 0) {
        printf("This word doesn’t occur in the text!");
    } else {
        printf("The word '%s' appears %d times in ham messages and %d times in spam messages.");
    }
    return countsh;
}

//this function gets the user input and saves the word for searching
char *getWord() {
    static char word[256];

    printf("Please enter a word to search for:\t");

    scanf("%255s", word);

    return word;
}

int main() {
    
    char *searchWord = getWord(); //assigning the searchword we got from the user to a var
    char *file = "preprocessed_dataset.txt";
    int *word_in_sh = countSH(file, searchWord);

    return 0;
}

唯一的警告是这个,我真的不明白问题是什么

try1_3.c: In function ‘countSH’:
try1_3.c:50:2: warning: function returns address of local variable [-Wreturn-local-addr]
  return countsh;
c segmentation-fault
1个回答
0
投票

语句

return countsh;
将数组
countsh
的地址返回给调用者,但该数组被定义为自动存储的本地对象,因此一旦函数返回,它就失效了。这是一个真正的问题,因为调用者无法可靠地读取该数组中的值。

您可以解决这个问题:

  • 通过提供目标数组作为参数
  • 或者将数组定义为
    static
    对象,但这将是一个快速而肮脏的修复,还会带来其他副作用,例如,如果多次调用
    countsh
    ,中间结果将被下一次调用覆盖。
© www.soinside.com 2019 - 2024. All rights reserved.