作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用这个代码片段:
// stackoverflow.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv)
{
int i;
int a[10];
// init
a[-1] = -1;
a[11] = 11;
printf(" a[-1]= = %d, a[11] = %d\n", a[-1], a[11]);
printf("I am finished.\n");
return a[-1];
}
编译器是Linux x86 的GCC。它运行良好,没有任何运行时错误。我还在 Valgrind 中测试了这段代码,它也不会触发任何内存错误。
$ gcc -O0 -g -o stack_overflow stack_overflow.c
$ ./stack_overflow
a[-1]= = -1, a[11] = 11
I am finished.
$ valgrind ./stack_overflow
==3705== Memcheck, a memory error detector
==3705== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3705== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==3705== Command: ./stack_overflow
==3705==
a[-1]= = -1, a[11] = 11
I am finished.
==3705==
==3705== HEAP SUMMARY:
==3705== in use at exit: 0 bytes in 0 blocks
==3705== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==3705==
==3705== All heap blocks were freed -- no leaks are possible
==3705==
==3705== For counts of detected and suppressed errors, rerun with: -v
==3705== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
根据我的理解,堆和栈是同一种内存。唯一的区别是它们以相反的方向生长。
所以我的问题是:
为什么堆上溢/下溢会触发朗姆时间错误,而堆栈上溢/下溢则不会?
为什么C语言设计者没有像堆一样考虑到这一点,而是将其保留为未定义行为
最佳答案
valgrind
不检测堆栈缓冲区溢出。使用AddressSanitizer。至少需要 gcc 4.8 并且必须安装 libasan。
gcc -g -fsanitize=地址 stackbufferoverflow.c
==1955==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x7fffff438d4c at pc 0x000000400a1d bp 0x7fffff438d10 sp 0x7fffff438d00
WRITE of size 4 at 0x7fffff438d4c thread T0
#0 0x400a1c in main /home/m/stackbufferoverflow.c:9
#1 0x7fe7e24e178f in __libc_start_main (/lib64/libc.so.6+0x2078f)
#2 0x400888 in _start (/home/m/a.out+0x400888)
Address 0x7fffff438d4c is located in stack of thread T0 at offset 28 in frame
#0 0x400965 in main /home/m/stackbufferoverflow.c:5
This frame has 1 object(s):
[32, 72) 'a' <== Memory access at offset 28 underflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-underflow /home/m/stackbufferoverflow.c:9 main
关于c - 为什么堆栈上溢/下溢不会触发运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556435/
我是一名优秀的程序员,十分优秀!