/* ** $Id: trash.cc 625 2007-03-23 05:50:52Z phf $ ** ** Example of "accidental" trashing of stuff on the stack. */ #include #include using std::cout; using std::endl; using std::hex; // It's a bad idea to return a pointer or a reference to // a local variable, something that got put on the stack // by the compiler. Here are two functions that do just // that, much to their detriment... int* bla() { int a = 0xAFFEAFFE; int *p = &a; return p; } int& blu() { int a = 0xCAFEBABE; int &r = a; return r; } // Here's another, unrelated function that uses some // stack space for a local string. It's going to trash // the values bla() or blu() left on the stack before. void argh() { char s[] = "Peter!"; } // And here is how it all works out... Enjoy! :-) int main() { cout << hex; int *x = bla(); cout << "*x: " << *x << endl; argh(); cout << "*x: " << *x << endl; int &y = blu(); cout << "y: " << y << endl; argh(); cout << "y: " << y << endl; } // Famous last words: I tried the "trashing" on several machines. // On my OS X laptop, parts of "a" get trashed, you can still see // a few bytes from the old patterns. On ugradx.cs.jhu.edu all of // "a" gets trashed. On qube.cs.jhu.edu "a" gets trashed right // away, i.e. even the first print right after bla() or blu() is // trashed already. Fascinating. :-)