简体   繁体   English

比较 c 中的两个 char 指针值时 strcmp 返回 true

[英]strcmp returning true when comparing two char pointer values in c

I am trying to compare the 2 passwords for authentication but it is returning true even if I have wrongly input the password.我正在尝试比较 2 个密码以进行身份验证,但即使我错误地输入了密码,它也会返回 true。 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");

}

The getpass function returns a pointer to a static buffer. getpass function 返回指向 static 缓冲区的指针。 This means that passwordFirst and passwordSecond point to the same place.这意味着passwordFirstpasswordSecond指向同一个地方。

You need to make a copy of the password returned from this function.您需要复制从该 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 .不要忘记freestrdup返回的 memory 。

You should copy the string pointed to by getpass when it returns, into a local buffer.您应该将getpass返回时指向的字符串复制到本地缓冲区中。 Otherwise, each pointer that you assign will point to the same internal buffer that getpass uses:否则,您分配的每个指针都将指向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");
}
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM