Lucas Phillips
Lucas Phillips

Reputation: 645

getpass() sets two strings the same?

I'm trying out getpass(), and I thought I'd try something:

char *key1 = getpass("K: ");
char *key2 = getpass("K: ");
if(key1 == key2) {

    printf("Good\n");

} else {

    printf("Bad\n");

}

If I write two different things in the two different fields, it will say "Good". I added a line to print the two strings, and it turns out they're both equal to whatever I type in the second one (typing "1" and "2" for key1 and key2 will result in both being equal to 2). What could be going on here?

Upvotes: 0

Views: 188

Answers (2)

alk
alk

Reputation: 70971

Use strdup() to duplicate a "string" and strcmp() to compare two "strings" by content.

Try this:

char * key1 = strdup(getpass("K: ")); 
char * key2 = strdup(getpass("K: ")); 

if (0 == strcmp(key1, key2)) 
{
  printf("Good\n");
}
else
{
  printf("Bad\n");
}

free(key1);
free(key2);

Also please note that getpass() is obsolete and shall not be used anymore!

Upvotes: 0

Mark Hendrickson
Mark Hendrickson

Reputation: 689

From the Linux man pages, getpass() returns a pointer to a static buffer, so every call to get pass will return the same address and the pointer stored in key1 will always equal the pointer stored in key2.

Return Value

The function getpass() returns a pointer to a static buffer containing (the first PASS_MAX bytes of) the password without the trailing newline, terminated by a null byte ('\0'). This buffer may be overwritten by a following call. On error, the terminal state is restored, errno is set appropriately, and NULL is returned.

You will need to make a local copy of each string returned by getpass() can then use (strcmp(key1Copy, key2Copy) == 0) to see if they are equal.

Upvotes: 2

Related Questions