c - 如何防止缓冲区溢出造成的密码屏蔽

标签 c buffer buffer-overflow masking

#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/

相关文章:

c - 在嵌入式应用中为什么c最受欢迎?

创建一个简单的单缓冲区应用程序 (IDirectDraw)

perl - 在 ubuntu 中使用 perl print 语句时 gdb 中的字节顺序被打乱

c - 覆盖主函数中的EIP

c - strcpy 的基本缓冲区溢出

c++ - 从文本控件中检索字符位置的客户区坐标

c - 当C库使用不透明结构指针时,如何解决cgo中的 "bad pointer in write barrier"panic

检查 char 变量的内容 - C 编程

c++ - Getline 不能循环工作

PHP - 如何有效地读取大型远程文件并在循环中使用缓冲区