为什么我在 C 中使用 fgets 时出现分段错误?

Why I got segmentation fault when using fgets in C?

我运行这个命令的程序:

./word_search oi < text.txt

并在 运行 时出现 分段错误

该程序旨在查找单词(作为命令行参数给出)在文件中的位置并打印出这些行。

#include <stdio.h>
#include "substring.c"

int main(int argc, char ** argv) {

    if(argc == 2) {
        char *str;
        while(fgets(str, 100, stdin)) {
            if(substring(str, argv[1]) != -1) {
                printf("Found: %s", str);
            }
        }
    }

    return 0;
}

如果我将 char *str 更改为 char str[100] 那么效果会很好。谁能告诉我为什么?
substring.c中的内容:

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

int substring(const char *line, const char *substr) {
    int i, j;
    int result;
    for(i = 0; i <= strlen(line)-strlen(substr); i++) {
        result = 0;
        if(line[i] == substr[0]) {
            int c = i;
            for(j = 0; j < strlen(substr); j++) {
                if (line[c] != substr[j]) {
                    result = -1;
                }
                c++;
            }
            if(result != -1)
                return i;
        }
    }
    return -1;

}

test.txt中的内容只是几行无意义的字符。

char *str 是一个单元化的指针,它不能保存你试图复制到其中的字符串,要么给它分配内存:

#include <stdlib.h>
#define SIZE 100

char *str = malloc(SIZE); //char has the size of 1 across platforms

或者简单地用你需要的大小声明它:

char str[SIZE];

将str的大小传给fgets

while(fgets(str, SIZE, stdin))

属于fgets

  • 您的容器将以 null 终止,它只能容纳 SIZE - 1 个字符的字符串。
  • SIZE - 1 以上的所有字符,包括 '\n' 将保持未读状态,因此在缓冲区中,您可能需要清除它。

我建议你花一些时间学习基本的 C。尤其是阅读指针,一开始它们有点难。

在您的示例中,str 是指向未定义内存位置的指针。