2012-04-06 100 views
3

是否有可能通过代码破坏c/C++中的调用堆栈? 我并不是指一种黑客攻击或某种东西,只是一种监督错误或某种东西,但不是随机的,这样每次都会损坏它。 有人告诉我,一位前同事管理,但我不认为这是可能的。 有人有这样的经历吗?破坏调用堆栈的C/C++代码

+0

在C/C++中损坏调用堆栈非常容易。这就是很多人讨厌他们的原因。 – iammilind 2012-04-06 12:22:09

回答

6

是的,简单。事实上,这是一个非常普遍的问题。考虑到这一点:

void foo() 
{ 
    int i; 
    int *p = &i; 
    p -= 5; // now point somewhere god knows where, generally undefined behavior 
    *p = 0; // boom, on different compilers will end up with various bad things, 
     // including potentially trashing the call stack 
} 

本地数组/缓冲区超出边界访问的许多情况都以最终的堆栈结束。

6

是的。在许多平台上,局部变量与调用堆栈一起存储;在这种情况下,写一个本地阵列外面是一个非常简单的方法来腐败吧:

void evil() { 
    int array[1]; 
    std::fill(array, array+1000000, 0); 
    return; // BOOM! 
} 

更微妙的是,返回一个参考给本地变量可能会破坏一个这就是所谓的后来函数的栈:

int & evil() { 
    int x; 
    return x; 
} 
void good(int & x) { 
    x = 0; 
    return; // BOOM! 
} 
void innocent() { 
    good(evil()); 
} 

请注意,这些(以及其他任何可能破坏堆栈的内容)都不合法;但编译器不需要诊断它们。幸运的是,只要启用适当的警告,大多数编译器都会发现这些错误。

+0

而我作为链接器的c变体会发现双重恶(double a); ... file1.h '双邪(双A);' file1.c中 的#include “file1.h” 双邪(双A){返回* 5;}' main.c中 的#include '双恶(空隙); //声明only' INT主(无效) { 的printf( “结果是%F,\ n” 个,恶());// BOOM return 0; } – 2012-04-06 12:10:19