简体   繁体   English

在C中使用strcmp进行分段错误?

[英]Segmentation Fault using strcmp in C?

I was getting Segmentation Fault (core dump) error when I run the code. 运行代码时出现分段错误(核心转储)错误。 After using some printf statement I found out that there is an error in strcmp part, maybe it's because comparing a char with a string? 使用一些printf语句后,我发现strcmp部分存在错误,可能是因为比较char和字符串? How do I fix this? 我该如何解决?

// 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;    
}

You have no guarantee that substring is non-NULL. 您不能保证substring为非NULL。 So you need to test it: 因此,您需要对其进行测试:

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;
}

Other problems: 其他问题:

  • In your code if (buff == NULL) break; 在您的代码中, if (buff == NULL) break; will never cause a break. 永远不会造成中断。 You need to test the return value of fgets . 您需要测试fgets的返回值。 (See WhozCraig's comment) (请参阅WhozCraig的评论)

  • fgets keeps the carriage-return, which is probably not what you want. fgets保留回车符,这可能不是您想要的。

  • The strstr/strcmp is confused: you probably just want strcmp , or maybe just strstr . strstr / strcmp感到困惑:您可能只想要strcmp ,或者只是strstr

  • If the file has a line longer than 1022 characters, then you might miss finding the string. 如果文件的行长超过1022个字符,则可能会找不到字符串。

The array buff is not null terminated. 数组buff不能为null终止。 You need to do that for the str... family of functions 您需要这样做是为了str...功能。

PS: Learn to indent the code PPS: Use a debugger to find of the value of buff PS:学习缩进代码PPS:使用调试器查找buff的值

if the buff is not NULL terminated, then problem will come in the strcmp . 如果buff不是NULL终止的,则问题将出现在strcmp In your case, initialize the buff variable(to zero) at the declaration part. 在您的情况下,请在声明部分将buff变量初始化为零。 Otherwise check the filesize and then add NULL character at the buff : 否则请检查filesize ,然后在buff处添加NULL字符:

[filesize+1]='\0'.
char *substring=strstr(buff, string);
    if ((strcmp(buff, substring)) == 0)
        return true;

char *substring in the case where you have a match, substring is pointing to somewhere inside buf if no match substring is pointing to NULL , and when you do strcmp(buff,substring) this will never be zero. char *substring在你有一个匹配的情况下, substring在里面BUF某处指着如果没有匹配substring指向NULL ,当你这样做strcmp(buff,substring)这将永远是零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM