有学生给我看了如下代码。
-------------
// Sina blog has bug, always stop me from pasting "% s" for formating a string
#include <stdio.h>
#include <string.h>
#define LEN 3
int main()
{
}
----------------------------------------------------------------------------
问我,为何在VC6.0中执行结果为
VC编译缺省4字节对齐,str2, str1地址相差4个字节,即比3大的4倍数最小是4,故有:
strcpy(str2,"222222")缓冲溢出后改写了str1, 导致str1被改写成"22".
同样的缓冲区溢出因为没有字节对齐(ADDR(str1)-ADDR(str2) == 3)而导致不同的输出。
此外,VC中因为4字节对齐,导致的缓冲区溢出只占用了本程序的合法空间,所以此时仍旧
是“安全的”,而codepad.org上的GCC因为没有4字节对齐,输入222222后,因为要在
str2+6加个0(即str1+3)加个0,已再次缓冲溢出。