简体   繁体   English

损坏调用堆栈的 C/C++ 代码

[英]C/C++ code that damages call stack

Is it possible an usual code to damage call stack in c/c++?是否有可能在 c/c++ 中损坏调用堆栈的常用代码? I don't mean a kind of hack or something, just an oversight mistake or something, but not random, such that damages it every time.我不是指某种黑客攻击或其他什么,只是一个疏忽错误或其他什么,但不是随机的,这样每次都会损坏它。 Someone told me that an ex colleague managed but I don't think it is possible.有人告诉我,一位前同事成功了,但我认为这不可能。 Does someone have such an experience?有人有这样的经历吗?

Yes, easy.是的,很简单。 One of the very common issues, in fact.事实上,这是非常常见的问题之一。 Consider this:考虑一下:

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
}

Many cases of an out-of-boundaries access of a local array/buffer end up with trashed stacks.许多越界访问本地数组/缓冲区的情况最终都会导致堆栈被破坏。

Yes.是的。 On many platforms, local variables are stored along with the call stack;在许多平台上,局部变量与调用堆栈一起存储; in that case, writing outside a local array is a very easy way to corrupt it:在这种情况下,在本地数组外部写入是破坏它的一种非常简单的方法:

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

More subtly, returning a reference to a local variable could corrupt the stack of a function that's called later on:更微妙的是,返回对局部变量的引用可能会破坏稍后调用的 function 的堆栈:

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

Note that neither of these (and indeed anything else that could corrupt the stack) are legal;请注意,这些(以及任何其他可能破坏堆栈的东西)都不合法; but the compiler doesn't have to diagnose them.但编译器不必诊断它们。 Luckily, most compilers will spot these errors, as long as you enable the appropriate warnings.幸运的是,只要您启用适当的警告,大多数编译器都会发现这些错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM