#include <conio.h>
#include <windows.h>
#include <stdio.h>
int main ()
{
char input[255];
int i = 0;
for(;;i++) /* Infinite loop, exited when RETURN is pressed */
{
char temp;
temp = getch (); /* Get the current character of the password */
if (GetAsyncKeyState (VK_RETURN)) /* If the user has pressed return */
{
input[i]='\0';
break;
}
input[i] = temp;
printf("*"); /* Print a star */
}
//printf("%s",input);
if(strcmp(input,"kamal")==0)
{
printf("ACCEPTED");
}
else
printf("not");
_getch();
return EXIT_SUCCESS; /* Program was executed successfully */
}
这是我的代码。如何防止缓冲区溢出,如果我输入更多密码,那么我的程序就会崩溃。无论如何我可以克服这个问题吗?
最佳答案
局部变量 char input[255] 存储在堆栈中。 C 中的数组没有边界检查。问题是,当我们添加超过 255 个字符时,存储在堆栈中的其他变量的值可能会发生变化。这可能会导致崩溃。
一种解决方案是读取字符并仅在范围 (i) 小于 255 时分配给输入数组。
#include <conio.h>
#include <windows.h>
#include <stdio.h>
int main ()
{
char input[255];
int i = 0;
int flag = 0;
for(;;i++) /* Infinite loop, exited when RETURN is pressed */
{
char temp;
temp = getch (); /* Get the current character of the password */
if (GetAsyncKeyState (VK_RETURN)) /* If the user has pressed return */
{
input[i]='\0';
break;
}
if ( i< 255)
{
input[i] = temp;
}
else
{
flag = 1;
}
printf("*"); /* Print a star */
}
//printf("%s",input);
if(strcmp(input,"kamal")==0 && flag == 0)
{
printf("ACCEPTED");
}
else
printf("not");
getch();
return EXIT_SUCCESS; /* Program was executed successfully */
}
另一个解决方案是动态分配(realloc())输入数组的大小。
关于c - 如何防止缓冲区溢出造成的密码屏蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15067223/