strcmp 在比较 C 中的两个字符指针值时返回 true



我正在尝试比较 2 个密码进行身份验证,但即使我输入了错误的密码,它也返回 true。我已经尝试了其他方法,但它不起作用。你能帮忙吗?

void registerUser() 
{
char userName[32];


printf("Maximum length for username is 32 characters longn");
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 matchn");
printf("passwd: Authentication token manipulation errorn");
printf("passwd: password unchangedn");
}

getpass函数返回指向静态缓冲区的指针。 这意味着passwordFirstpasswordSecond指向同一个位置。

您需要复制从此函数返回的密码。

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

不要忘记freestrdup返回的记忆。

getpass返回时,应将它指向的字符串复制到本地缓冲区中。否则,您分配的每个指针都将指向getpass使用的同一内部缓冲区:

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");
}
// ...

最新更新