strcmp returning true when comparing two char pointer values in c

Viewed 103

I am trying to compare the 2 passwords for authentication but it is returning true even if I have wrongly input the password. I have tried other ways but it is not working. Can you help?

void registerUser() 
{
 char userName[32];





printf("Maximum length for username is 32 characters long\n");
printf("Enter username: ");
scanf("%s",userName);


char *passwordFirst = getpass("Enter new UNIX password: ");


char *passwordSecond = getpass("Retype new UNIX Password: ");



if (strcmp(passwordFirst,passwordSecond)==0)
{
    printf("GOOD");
}

else
{

    printf("Sorry, passwords do not match\n");
    printf("passwd: Authentication token manipulation error\n");
    printf("passwd: password unchanged\n");

}
2 Answers

The getpass function returns a pointer to a static buffer. This means that passwordFirst and passwordSecond point to the same place.

You need to make a copy of the password returned from this function.

char *passwordFirst = strdup(getpass("Enter new UNIX password: "));
char *passwordSecond = strdup(getpass("Retype new UNIX Password: "));

Don't forget to free the memory returned from strdup.

You should copy the string pointed to by getpass when it returns, into a local buffer. Otherwise, each pointer that you assign will point to the same internal buffer that getpass uses:

char passwordFirst[33] = ""; // Initialise all chars to zero...
strncpy(passwordFirst, getpass("Enter new UNIX password: "), 32);
char passwordSecond[33] = "";// ... so "strncpy" will be safe if >32 chars given
strncpy(passwordSecond, getpass("Retype new UNIX Password: "), 32);

if (strcmp(passwordFirst, passwordSecond)==0)
{
    printf("GOOD");
}
// ...
Related