C GOTO命令创建无限循环

nul*_*ull 1 c goto

#include <stdio.h>

int main(void)
{
    char str[10];int i,length=0;
    line:
    { 
        printf("Enter string of length 10 \n");
        scanf("%[A-Za-z]s", str);
    }
    for (i=0; str[i] != '\0'; i++)
    {
        length++;
    }
    if (length != 10)
    {
        printf("Length of string is : %d \n Give a string of length 10 please \n", length);
        goto line;
    }
    else 
    {
        printf("length = %d \n", length);
        printf("Your String is: %s", str);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果用户输入长度不等于10的字符串,那么我的预期输出应为:打印输出"输入字符串长度为10"并等待用户输入另一个字符串然后检查它的长度.

我已经删除了Goto语句并检查了长度不等于10的字符串,它确实计算了长度并输出它,如下所示:

Enter string of length 10 
dciciibiyciyigiy
Length of string is : 16 
Give a string of length 10 please. 
*** stack smashing detected ***: ./palindrome.out terminated
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

我在其他地方的其他代码中执行了类似的Goto命令执行,但对于这个:如果我尝试输入一个长度不等于10的字符串,它会显示长度,然后进入无限循环o打印如下所示:

...
Length of string is : 428115 
Give a string of length 10 please. 
Enter string of length 10 
Length of string is : 428130 
Give a string of length 10 please. 
Enter string of length 10 
Length of string is : 428145 
Give a string of length 10 please. 
...
Run Code Online (Sandbox Code Playgroud)

等等.我不明白我做错了什么?

dbu*_*ush 5

您没有正确限制用户可以输入的字符数.

该数组str可以容纳10个字节,但调用scanf不会限制用户输入更多字符.因此,如果输入的字符太多,则可以写入数组的末尾.这会调用未定义的行为,在这种情况下会导致代码崩溃.

您需要将格式说明符更改scanf为允许最多9个字符(因为您需要为空终止字符保存1个字节):

scanf("%9[A-Za-z]", str);
Run Code Online (Sandbox Code Playgroud)

然后,您可以删除长度检查(以及相关联的goto),因为无法再输入10或更长的字符串.

如果您希望用户最多可以输入10个字符,则需要将大小str增加到11.