我正在尝试 getpass()
,我想我应该尝试一下:
char *key1 = getpass("K: ");
char *key2 = getpass("K: ");
if(key1 == key2) {
printf("Good\n");
} else {
printf("Bad\n");
}
如果我在两个不同的领域写两个不同的东西,它会说“好”。我添加了一行来打印这两个字符串,结果发现它们都等于我在第二个字符串中键入的任何内容(为 key1 和 key2 键入“1”和“2”将导致两者都等于 2)。这里会发生什么?
最佳答案
在 Linux 手册页中,getpass()
返回一个指向静态缓冲区的指针,因此每次调用 get pass 都会返回相同的地址和存储在 key1
中的指针> 将始终等于存储在 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.
您需要为 getpass()
返回的每个字符串制作一个本地副本,然后可以使用 (strcmp(key1Copy, key2Copy) == 0)
查看是否他们是平等的。
关于c - getpass() 设置两个字符串相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19921729/