如何解决编译下面的代码时出现的堆栈粉碎错误?

时间:2013-03-29 06:00:10

标签: c string

main()
{
    char a[20];
    int b;
    printf("\n enter your name");
    a[20]=getchar();
    printf("\n enter your password");
    scanf("%d",&b);
    if (a=="ilangeeran")
    {
        printf("\n login successful");
    }
}

这是示例程序,在编译此堆栈时会发生粉碎错误如何解决此错误?

1 个答案:

答案 0 :(得分:5)

您对a的声明指定了一个包含20个字符的数组:a[0]a[19]a[20]超出范围:a[20]=getchar();

getchar返回int。它这样做是为了区分非字符EOF值和有效字符值。任何正回报值都是一个字符。任何负值都是错误...但您需要将返回值存储在int 中并检查该值是否为负值以便处理错误!

int c = getchar();
if (c < 0) {
    fputs("Read error while reading from stdin", stderr);
    return EXIT_FAILURE;
}
a[19] = c; /* Don't rely on this being a string, since a string is a sequence of
            * characters ending at the first '\0' and this doesn't have a '\0'.
            * Hence, it isn't a string. Don't pass it to any str* functions! */

同样,你应该处理来自scanf的错误:

switch (scanf("%d", &b)) {
    case 1: /* excellent! 1 means that one variable was successfully assigned a value. */
            break;
    case 0: fputs("Unexpected input while reading from stdin; "
                  "The \"%d\" format specifier corresponds to decimal digits.", stderr);
            return EXIT_FAILURE;
    default: fputs("Read error while reading from stdin", stderr);
             return EXIT_FAILURE;
}

if (a=="ilangeeran")是无稽之谈。你正在读哪本书?