繁体   English   中英

在本地PC上运行的C回文程序,但在INGInious上不运行

[英]C palindrome program working on local PC, but not on INGInious

我有一个检测回文的交流程序。 它还可以检测到带有空格的回文。 如果字符串为null,则返回-1,如果是回文,则返回1,否则返回0。 这是代码:

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

int pal(char *str){

    if(str[0] == '\0'){
        return -1;
    }else{
        size_t i = 0;
        size_t j = strlen(str) - 1;
        while(*(str + i) != '\0'){
            if(*(str + i) == ' '){
                i++;
                continue;
            }else if(*(str + j) == ' '){
                j--;
                continue;
            }else{
                if(*(str + i) != *(str + j)){
                    return 0;
                }
            }
            i++;
            j--;
        }

        return 1;

    }

}


int main(){

    char *str = "a man a plan a canal panama";
    printf("%d", pal(str));
    printf("\n");
    return 0;
}

当我在本地计算机上编译并运行该程序时,它运行良好。 但是,当我将其上传到我的CS课程的INGInious问题(INGInious是一个平台,人们可以在该平台上上传关于特定主题的答案并由系统对其进行复查)时,它会导致细分错误。 是否有可能导致我不知道的SegFault的情况?

就像我在评论中说的那样,您并没有控制j值,因此,您的代码可能会表现出不确定的行为 -当j变为0时,但您不断减小它,它会回绕并成为size_t类型的最大值(在现代平台上相当可观的数字)。

您提供的字符串不会发生这种情况,但是,我想您的测试平台会在另一个字符串上对其进行测试(这是我对崩溃的唯一解释)。

例如,您的代码将暴露于以下字符串上的未定义行为: "a bcd"

您的代码太复杂了。

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

bool is_palindrome(char const *str)
{
    size_t length = strlen(str);

    for (char const *front = str, *back = str + length - 1; front != back; ++front, --back) {
        while (isspace((char unsigned) *front) && front != str + length - 1)
            ++front;

        while (isspace((char unsigned) *back) && back != str)
            --back;

        if (front == back)
            break;

        if (*front != *back)
            return false;
    }
    return true;
}

int main(void)
{
    char const *foo = "a man a plan a canal panama";
    printf("%d\n", is_palindrome(foo));

    char const *bar = "hello";
    printf("%d\n", is_palindrome(bar));
}

输出:

1
0

在下面的循环中:

while(*(str + i) != '\0'){
    if(*(str + i) == ' '){
        i++;
        continue;
    }else if(*(str + j) == ' '){
        j--;
        continue;
    }else{
        if(*(str + i) != *(str + j)){
            return 0;
        }
    }
    i++;
    j--;
}

*(str + i) == '\\0' ,应该是i == strlen(str)j == -1 (如果字符串中没有空格。否则我不太确定),那可能就是问题。 但是再次,我看不到您不会访问超出范围的str 我建议这样做,以使您的循环更容易看到终止条件:

while(i < j){
    // ...
}

暂无
暂无

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

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