Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp returning true when comparing two char pointer values in c

Tags:

c

linux

unix

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");

}

1 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.

like image 186
dbush Avatar answered Aug 18 '26 17:08

dbush