C缓冲区溢出的说明 [英] Explanation of C buffer overflow
问题描述
我尝试了解缓冲区溢出.这是我的代码:
I try to understand buffer overflows. This is my code:
#include <stdio.h>
int main()
{
char buf[5] = { 0 };
char x = 'u';
printf("Please enter your name: ");
gets(buf);
printf("Hello %s!", buf);
return 0;
}
buf
数组的大小为5,并以0es初始化.因此(使用零终止符)我有四个字符的空间.如果输入五个字符(例如,堆栈),我将覆盖空终止符,并且 printf
应该打印"Hello stacku!".由于后面的变量 x
.但是事实并非如此.它只是打印堆栈".有人可以解释为什么吗?
The buf
array is of size five and initialized with 0es. So (with null termination) I have space for four characters. If I enter five characters (stack for example), I overwrite the null termination character and printf
should print "Hello stacku!" because of the succeeding variable x
. But this isn't the case. It simply prints "stack". Could someone please explain why?
推荐答案
局部变量通常在堆栈上创建.在大多数实现中,随着分配内存,堆栈向下增长,而不是向上增长.因此,很可能 buf
的地址比 x
的地址高.这就是为什么当 buf
溢出时,它不会覆盖 x
的原因.
Local variables are generally created on the stack. In most implementations, stacks grow downward, not upward, as memory is allocated. So, it is likely that buf
is at a higher address than x
. That's why, when buf
overflows, it does not overwrite x
.
您也许可以通过编写 buf [-1] ='v'; printf(%c \ n",x);
来确认这一点,尽管这可能会受到填充的影响.将地址与 printf(%i \ n",buf-& x);
进行比较也可能很有启发性-如果结果为肯定,则 buf
地址比 x
更高.
You might be able to confirm this by writing buf[-1]='v';printf("%c\n",x);
although that might be affected by padding. It may also be instructive to compare the addresses with printf("%i\n",buf - &x);
-- if the result is positive, then buf
is at a higher address than x
.
但这全都高度依赖于实现,并且可以根据各种编译器选项进行更改.正如其他人所说,您不应依赖任何这些.
But this is all highly implementation dependent, and can change based on various compiler options. As others have said, you shouldn't rely on any of this.
这篇关于C缓冲区溢出的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!