程序在运行期间破坏了已在操作系统里定义好的栈边界,这种行为具有破坏性,操作系统使用stack smashing detect机制来检测栈溢出。
实例一:
- #include
- #include
- #define MAXSIZE 3
- int main() {
- char buf[MAXSIZE] = { 0 };
- scanf("%s", buf);
- puts(buf);
-
- return 0;
- }
编译程序gcc -g -o Test test.c
输入如下所示:
此时,程序已被操作系统abort,因为操作系统已检测出了栈溢出。
实例二:
- #include
- #include
- #include
- #define MAXSIZE 3
- int fun() {
- char buf[MAXSIZE] = { 0 };
- memcpy(buf, "0123456789", 10);
- puts(buf);
- return 0;
- }
- int main() {
- fun();
- return 0;
- }
编译程序gcc -g -o Test test.c
输入如下所示:
valgrind ./Test --leak-check=full
输出如下图所示:
valgrind会输出有栈溢出的行数,例如test.c:12就是main函数调用fun的行数
1.使用objdump反汇编二进制
objdump -D Test #Test是刚才栈溢出的程序编译的二进制
2.__stack_chk_fail调用流程
__stack_chk_fail =>fortify_fail=>libc_message
1.栈溢出有时来源于程序编制的漏洞,在对栈进行操作时,注意检查边界值;
2.使用更安全的库函数,比如使用fgets替代scanf
- #include
- #include
- #define MAXSIZE 3
- int main() {
- char buf[MAXSIZE] = { 0 };
- fgets(buf, sizeof(buf), stdin); // 最多输入MAXSIZE - 1个字符
- puts(buf);
-
- return 0;
- }
也可以使用C++ cin.get,例如std::cin.get(buf, MAXSIZE);