C 缓冲区溢出测试 - 64 位上的段错误不应该发生?

C Buffer overflow test - Seg fault on 64 bit when it shouldn't?

我有以下用于测试缓冲区溢出的代码:

#include <stdio.h>
#include <string.h>

int PasswordOkay() {
    char GoodPassword = 'F';
    printf("The memory address of GoodPassword is: %p\n", (void*) &GoodPassword);
    char Password[8];
    printf("The memory address of password is: %p\n", (void*) &Password);
    gets(Password);

    if(!strcmp(Password, "SPOCKSUX"))
        GoodPassword = 'T';
    return (GoodPassword == 'T');
}

int main() {
    puts("Enter Password:");
    if(PasswordOkay())
        puts("Hello, Dr. Bones");
    else
        puts("Access denied.");
}

在 32 位上,溢出工作正常,9T 作为密码让我成功登录。

在 64 位上,我有这些内存地址:

The memory address of GoodPassword is: 0x7fff1b452a8f
The memory address of password is: 0x7fff1b452a80

所以为了尝试那里的溢出,我将 16T 作为密码。登录消息再次出现成功,但它也给出了分段错误。(32 位没有)。

我的问题是:为什么在 64 位上会出现分段错误?不应该吗?因为我只是覆盖 GoodPassword.

补充说明:文件是用 gcc 编译的,尝试打开和关闭优化器。

您的缓冲区溢出没问题,但并非所有缓冲区溢出都以分段错误结束。这取决于您编写的内容、位置、您的程序(或运行时库)随后执行的操作 - 各种因素。

您输入了 16 个字符 (TTTTTTTTTTTTTTTT) 但您还必须将字符串的终止空字符视为第 17 个字符,这意味着在 GoodPassword 之后另一个字节也会在堆栈中被覆盖框架。

GoodPasswordpassword 之间的地址差异是 15 (0x7fff1b452a8f - 0x7fff1b452a80),这意味着 GoodPassword 是第 16 个字符,您的地址中还有一个差一个具有空字节的堆栈帧。

如果紧随其后的字节(堆栈上部 GoodPassword)是帧指针地址或保存的堆栈指针地址(甚至是安全金丝雀值!)的一部分,您可能会遇到段错误。