如何在使用fgets的c程序中溢出此缓冲区

  • 本文关键字:程序 溢出 缓冲区 fgets c
  • 更新时间 :
  • 英文 :

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int x;

int main(int argc, char **argv)
{
char buffer[2];
x = 0;
puts("please enter textn");
fgets(buffer, 200, stdin);
printf("You have entered: " );
printf( buffer );
printf("nhidden->%d",x);
}

无论输入没有溢出,它都会吐出长度超过20的文本,我不明白为什么,我怎么能溢出它(char缓冲区[2](?它是用编译的

`gcc -g -O0 -mpreferred-stack-boundary=2 -m32 -fno-stack-protector -z execstack` -D_FORTIFY_SOURCE=0 test.c && mv a.out test.o

缓冲区确实溢出,但可能您没有看到。请注意,buffer在堆栈上,溢出发生在那里。变量x没有在堆栈上分配,因此它很可能会受到溢出的影响。

稍微修改一下代码,您就可以看到溢出:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int x;
char buffer[2];
x = 0;
puts("please enter textn");
fgets(buffer, 200, stdin);
printf("You have entered: " );
printf( buffer );
printf("nhidden->%d",x);
return EXIT_SUCCESS;
}

编辑:看评论,这些都是完全正确的。