c - 在 C 中使用 strcmp 的段错误?

标签 c string segmentation-fault strcmp

我在运行代码时收到段错误(核心转储)错误。在使用一些 printf 语句后,我发现 strcmp 部分有错误,可能是因为将 char 与 string 进行比较?我该如何解决这个问题?

// this function checks if the file contains the *string

bool checkIfMatch(char *string, FILE *file) {

    while (true) {

        char buff[1024];
        fgets(buff, sizeof buff, file);
        if (buff == NULL)
            break;

        char *substring=strstr(buff, string);
        if ((strcmp(buff, substring)) == 0)
            return true;
    }

    return false;    
}

最佳答案

您不能保证 substring 是非 NULL。所以你需要测试它:

bool checkIfMatch(char *string, FILE *file) {
    char buff[1024];
    while (fgets(buff, sizeof buff, file)) {
        char *substring=strstr(buff, string);
        if (substring && !strcmp(buff, substring)) 
            return true;
    }
    return false;
}

其他问题:

  • 在您的代码中,if (buff == NULL) break; 永远不会导致中断。您需要测试fgets 的返回值。 (参见 WhozCraig 的评论)

  • fgets 保留回车符,这可能不是您想要的。

  • strstr/strcmp 很困惑:您可能只需要 strcmp,或者可能只需要 strstr

  • 如果文件中的一行超过 1022 个字符,那么您可能会找不到字符串。

关于c - 在 C 中使用 strcmp 的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21655050/

相关文章:

c - 嵌入式系统中的内存使用

c++ - recv() 套接字循环永远不会结束 C

Python-删除字符串中最后一个字母之前的所有字符

c - 单列 gtktreeview 行为正确,但多列给出段错误

c++ - 为什么将 'char' 分配给 'char' 会产生段错误? C++

C 编程使用 free() 时出现 "Segmentation fault (core dumped)"

c - x86 中 stat 结构的布局

c - 如何使用 C 获取 Linux 中的 CPU 数量?

python - 如何插入双字母

C - 将字符串保存到数组元素中