简体   繁体   中英

C/C++ code that damages call stack

Is it possible an usual code to damage call stack in 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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