为什么我在 运行 代码上收到调试断言失败错误

Why am I getting a debug assertion failed error on running the code

当我在下面的程序中输入密码并按回车键时,我得到了调试 断言错误,特别是 isctype.c 行 56

表达式:(无符号)(c+1) <= 256

有人可以帮我解决这个问题吗?

代码:

int main()
{
        int j=0;
        char pass[100];
        int upper=0, lower=0, digit=0, sc=0;

        printf("Enter your password:\n");
        scanf("%s",&pass);

        while(j!=' '){
                if(isalpha(pass[j])){
                        if(isupper(pass[j])){
                                upper++;
                        }
                        else{
                                lower++;
                        }
                }
                else if(isdigit(pass[j])){
                        digit++;
                }
                else{
                        sc++;
                }
                j++;
        }

        if(upper==0||lower==0||digit==0||sc==0){
                printf("Password must contain atleast one upper case, one lower case, one digit and a special character");
        }
        else{
                printf("Good to go");
        }
        return 0;
        _getch();
}

看起来你的代码中的问题是

while(j!=' ')

正在检查 j 与 space (' ') 的 ASCII value 为 32(十进制)。

本质上,您无条件地使用 pass 索引为 0 到 31 的数组元素。

那么,pass是一个自动局部变量,你没有初始化它。它包含不确定的值。

如果您的输入少于 31 个字符,pass 的剩余元素将保持未初始化状态,进一步使用它们(作为 is....() 系列的参数,此处)可能会导致 undefined behaviour.

解决方案: 您不需要检查 space,(因为 %s 不接受)。相反,您应该检查空终止符 [=18=]。将您的代码更改为

  1. scanf("%s",&pass);scanf("%99s",pass); 以避免可能的缓冲区溢出。
  2. while(j!=' ')while(pass[j]) 循环直到字符串终止符为 null。

也就是说,

  • unconditional return 语句之后使用 _getch() 没有任何意义。您可以直接删除 _getch().
  • main()的推荐签名是int main(void).

替换

while (j!=' ')

来自

while (pass[j] != 0)

只要 pass[j] 不为零就可以循环。请记住,字符串以零结尾。