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

301 Views Asked by At

When I enter a password in my program below and press enter I get a debug assertion error, specifically isctype.c line 56

Expression:(unsigned)(c+1) <= 256

Could someone help me get around this please?

Code:

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();
}
2

There are 2 best solutions below

0
On BEST ANSWER

Replace

while (j!=' ')

by

while (pass[j] != 0)

You want to loop as long as pass[j] is different from zero. Remember, strings are terminated by a zero.

0
On

It looks like the problem in your code is

while(j!=' ')

which is checking j against space (' ') which is having ASCII value of 32 (decimal).

Essentially, you're unconditionally using pass array elements having index 0 to 31.

Then, pass is an automatic local variable and you did not initialize it. It contains indeterminate value.

If, your input is less than 31 characters, the remaining element of pass will remain uninitialized, and using them further (as the argument to is....() family, here) may lead to undefined behaviour.

Solution: You don't need to check for a space, (as %s does not accept one). Instead you should check for the null terminator \0. Change your code to

  1. scanf("%s",&pass); to scanf("%99s",pass); to avoid possible buffer overflow.
  2. while(j!=' ') to while(pass[j]) to loop until the string terminator null.

That said,

  • using _getch() after unconditional return statement does not make any sense. You can straight-away remove that _getch().
  • The recommended signature of main() is int main(void).