我是 C 的新手,所以我开始玩一些代码。我的代码中有一个错误,因为我认为使用使用printf(pass)不安全,因为它可以覆盖该值,因此对用户不安全。我想知道printf(pass)我的代码不安全是否正确?另外,我怎样才能让用户在finally logged in不更改代码的情况下打印消息。有没有办法做到这一点?
我的代码:
#include <stdio.h>
char pass[100];
char getPass() {
int value = 'G';
int * j = & value;
fgets(pass, sizeof(pass), stdin);
printf("your entered pass is ");
printf(pass);
return (char)( * j);
}
void main() {
printf("enter the pass here ");
if (getPass() == 'K') {
printf("finally logged in\n");
exit(0);
} else {
printf("Wrong password\n");
exit(1);
}
}
Run Code Online (Sandbox Code Playgroud)
是的,这是不安全的,但不是因为您建议的原因。如果您查看该函数的man页面printf(),您会看到它具有以下原型:
int printf(const char * restrict format, ...);
Run Code Online (Sandbox Code Playgroud)
const应用于第一个参数的修饰符指定调用此函数时不会更改此参数的值。
但是,您还会注意到此参数称为format。那是因为它应该指定一个格式字符串。在您的程序中,没有什么可以阻止用户输入像 那样的格式说明符%p,在这种情况下,您的调用printf()将开始打印堆栈的内容。有一篇维基百科文章更详细地描述了这个漏洞。