C / C ++ code that breaks the call stack
Can normal code be used to corrupt the call stack in c / C ++? I don't mean some kind of hack or anything like that, just an oversight bug or something like that, but not an accident that hurts it every time. Someone told me that a former colleague was in charge, but I don't think that's possible. Does anyone have this experience?
source to share
Yes Easy. Actually one of the most common problems. 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 out-of-bounds access to a local array / buffer end up with split stacks.
source to share
Yes. On many platforms, local variables are stored with the call stack; in this case writing outside of the local array is a very simple way to mess it up:
void evil() {
int array[1];
std::fill(array, array+1000000, 0);
return; // BOOM!
}
More subtly, returning a reference to a local variable can damage the stack of a function called later:
int & evil() {
int x;
return x;
}
void good(int & x) {
x = 0;
return; // BOOM!
}
void innocent() {
good(evil());
}
Note that none of these (and even nothing that could damage the stack) were legal; but the compiler shouldn't diagnose them. Fortunately, most compilers will find these errors if you include the appropriate warnings.
source to share