首页 > 解决方案 > 此代码如何破坏我的堆栈跟踪?

问题描述

这个简单的测试程序,

$ cat crash.c 
int main() {
    int x = 0;
    *(&x + 5) = 10;
    return 0;
}

使用 GCC 7.4.0 编译,

$ gcc -O0 -g crash.c

有意外的堆栈跟踪

$ ./a.out 
Segmentation fault (core dumped)
$ gdb ./a.out /tmp/wk_cores/core-pid_19675.dump
Reading symbols from ./a.out...done.
[New LWP 19675]
Core was generated by `./a.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00007f450000000a in ?? ()
(gdb) bt
#0  0x00007f450000000a in ?? ()
#1  0x0000000000000001 in ?? ()
#2  0x00007fffd6f97598 in ?? ()
#3  0x0000000100008000 in ?? ()
#4  0x00005632be83d66a in frame_dummy ()
Backtrace stopped: previous frame inner to this frame (corrupt stack?)

我不明白为什么堆栈不向特权内存显示无效存储?有人可以帮我理解这一点吗?

标签: cgdb

解决方案


我不明白为什么堆栈不向特权内存显示无效存储?

因为您没有将任何内容存储到特权内存中。

为此,您需要在堆栈之外编写方式,例如:

*(&x + 0x10000) = 5;

照原样,您的程序确实表现出未定义的行为,但它不会写入“特权”内存,只是写入可写但您不应该写入的内存。


推荐阅读