Reputation: 73443
In C++, in which way can the stack get corrupted? One way I guess is to overwrite the stack variables by accessing an array beyond its boundaries. Is there any other way that it can get corrupted?
Upvotes: 20
Views: 38575
Reputation: 4109
Violations of the One Definition Rule can lead to stack corruption. The following example looks stupid, but I've seen it a couple of times with different libraries compiled in different configurations.
struct MyStruct
{
int val;
#ifdef LARGEMYSTRUCT
char padding[16];
#endif
}
#define LARGEMYSTRUCT
#include "header.h"
//Here it looks like MyStruct is 20 bytes in size
void func(MyStruct s)
{
memset(s.padding, 0, 16); //corrupts the stack as below file2.cpp does not have LARGEMYSTRUCT declared and declares Mystruct with 4 bytes
return; //Will probably crash here as the return pointer has been overwritten
}
#include "header.h"
//Here it looks like MyStruct is only 4 bytes in size.
extern void func(MyStruct s);
void caller()
{
MyStruct s;
func(s); //push four bytes on to the stack
}
Upvotes: 38
Reputation: 6145
Throwing an exception inside a destructor is a good candidate. It would mess up the stack unwinding.
Upvotes: 5
Reputation: 53310
But those are not particular to C++, which doesn't have any idea of the stack.
Upvotes: 40
Reputation: 1985
Taking pointers to stack variables is a good way:
void foo()
{
my_struct s;
bar(&s);
}
If bar keeps a copy of the pointer then anything can happen in the future.
Summing up: Stack corruption happens when there's stray pointers pointing to the stack.
Upvotes: 16
Reputation: 41096
Calling a function with the wrong calling convention.
(though this is technically compiler-specific, not a question of C++, every C++ compiler has to deal with that.)
Upvotes: 5
Reputation: 111130
The C++ standard does not define stack/heap. Further, there are a number of ways to invoke undefined behavior in a program -- all of which may corrupt your stack (it's UB, after all). The short answer is -- your question is too vague to have a meaningful answer.
Upvotes: 8