Reputation: 213
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?
Upvotes: 3
Views: 382
Reputation: 254631
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.
Upvotes: 6
Reputation: 20272
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.
Upvotes: 6