Home > Software engineering >  Compare password to a given set of passwords
Compare password to a given set of passwords

Time:12-05

I have got an assignment from uni which mentions that I have to compare a given set of passwords to the password given by the user. The set of passwords are predetermined in the question as follows

const char *passwd[NUM_PASSWDS] = {
    "123foo", "bar456", "bla_blubb"
};

and has to be compared with input from user...

So I have written my code as follows;

#include <stdio.h>
#include <string.h>

#define NUM_PASSWDS 3

const char *passwd[NUM_PASSWDS] = {
    "123foo", "bar456", "bla_blubb"
};

int pwdquery(char pass[]) {
    for (int i = 0; i < 2; i  ) {
        if (passwd[i] == pass[i]) {
            return printf("correct");
        }
    }
}

int main() {
    char a[100];
    for (int i = 0; i < 3; i  ) {
        printf("Please enter password");
        scanf("%s", a);
    }
    pwdquery(a);
}

When I tried running my code, it shows an error...

Thank you for your time

CodePudding user response:

There are multiple problems in your code:

  • the password comparison function pwdquery compares a character and a pointer: this is incorrect. You should use strcmp to compare the strings and return a non zero value if one of these comparisons returns 0.

  • in the loop, you ask for the password 3 times, but you only check the password after this loop, hence only test the last one entered.

  • scanf("%s", a) may cause a buffer overflow if the user enters more than 99 characters without white space. Use scanf("

  • Related