为什么在访问整数时缓冲区溢出会导致分段错误?

2022-01-12 00:00:00 c segmentation-fault c++ buffer-overflow

在从函数 A() 调用函数 B() 期间,B() 分配一个 100 字符的数组并多次填充,包括一次使用 101 字符的字符串和一次使用 110 字符的字符串.这是一个明显的错误.

During a call to function B() from function A(), B() allocates a 100-char array and fills it several times, including once with a 101-character string and once with a 110 character string. This is an obvious mistake.

后来,函数 A() 尝试访问完全不相关的 int 变量 i,结果出现分段错误.

Later, function A() tries to access completely unrelated int variable i, and a segmentation fault occurs.

我明白为什么会发生缓冲区溢出,但是为什么我在访问这个整数时会出现分段错误?为什么我不简单地获取垃圾数据?

I understand why the buffer overrun occurs, but why do I get a segmentation fault when I access this integer? Why is it that I don't simply get garbage data?

推荐答案

A()调用B()时,B的前导指令保存了A的帧指针――位置在 A 保存局部变量的堆栈上,然后用 B 自己的帧指针替换它.它看起来像这样:

When A() calls B(), B's preamble instructions save A's frame pointer―the location on the stack where A keeps local variables, before replacing it with B's own frame pointer. It looks like this:

当 B 超出其局部变量时,它会弄乱将重新加载到帧指针中的值.这是作为帧指针值的垃圾,因此 A 的所有局部变量都被丢弃.更糟糕的是,未来对局部变量的写入会扰乱属于??其他人的内存.

When B overruns its local variables, it messes up the value which will be reloaded into the frame pointer. This is garbage as a frame pointer value, so all of A's local variables are trashed. Worse, future writes to local variables are messing with memory belonging to someone else.

相关文章