0

I started learning C some days ago and I have come across a problem I have no idea why it occurs. The program below asks the user to enter a password and ensures that the password is inputted twice so they do not create an unwanted password by mistake.

However, there seems to be for some reason a stack overflow with the variables password and probably SecondPassword because in the outermost printf (printing "Now the password is...") in which I display the value of password, it contains twice the password inputted by the user.

I am sure it has something to do with the while-loop but I cannot determine why it is behaving unexpectedly. Can anyone shed some light on this?

Many thanks.

    char password [10];
    char SecondPassword [10];
    
    
    //Ask for password
    strcpy(password,"foo"); // to initiliaze password to a smaller than 10 length
    strcpy(SecondPassword,"boo");
    while (strncmp(password,SecondPassword,10)!=0 ){
        printf("Enter a 10-digit password\n"); //not inside the innermost loop to avoid showing it twice
        while (strlen(password)!=10){
            
            scanf("%s", password);
            printf("The password is %s\n", password);
        }
        printf("Enter your password again\n");
        scanf("%s", SecondPassword);
        printf("Now the password is %s\n", password);
    }``
Oriol
  • 75
  • 5

0 Answers0