当尝试运行以下程序时:-
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("HI whats your name? ");
char name;
scanf("%s",&name);
printf("So your name is %s ", name);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是当尝试运行我的代码时,我收到一条错误消息
Process terminated with status -1073741819 (0 minute(s), 11 second(s))
Run Code Online (Sandbox Code Playgroud)
我不知道这个错误意味着什么。该程序是一个非常简单的 C 程序,用于将名称作为输入并向用户打招呼。请告诉我如何修复这个错误。
char name;
Run Code Online (Sandbox Code Playgroud)
仅为名称保留一个字节,因此当您输入名称时,它会产生缓冲区溢出,从而产生内存违规错误。使用 char 数组代替:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("HI whats your name? ");
char name[256]; //Note we are reserving space for up to 255 chars,
//because the 256th must be reserved for the ending null.
scanf("%s",name); //Note also that we don't use the & because an array is already a pointer
printf("So your name is %s ", name);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
缓冲区溢出是一个过程,您尝试在缓冲区中填充超出其大小可以容纳的项目。在您的情况下,您开始将名称字符存储在变量的位置name,并继续存储在以下存储单元中,最终覆盖其后面的变量。
此外,由于该变量name是自动变量,因此它驻留在堆栈中。当您存储输入字符时,也会覆盖返回地址,在大多数系统中,返回地址保存在同一堆栈上,结果是,当从函数返回时,处理器会跳转到错误的地址。
如果巧合,缓冲区溢出可以主动更改返回地址,以强制处理器执行恶意代码。所谓的“缓冲区溢出漏洞利用”。