On Wed, 17 Sep 2008 20:04:26 -0700, Tim Sprout <tm**@ptialaska.netwrote:
Below is code based on the tutorial at
http://tinyurl.com/3f3zy9
Why does the MessageBox show the correct value of 30 when debugging
without breakpoints, but shows a value of zero when adding a breakpoint
within Method(), and stepping through?
I think a more interesting question is "why does the MessageBox show the
correct value of 30 _ever_?" :)
It is a _really_ bad thing to return the address of a local variable.
Once the method returns, that local variable doesn't exist any more. The
address that pointed to the local variable when it did exist simply points
to where it _used_ to be in the stack.
Obviously in the "no breakpoint" scenario, the program gets lucky and
nothing got written to the location in memory by the time the address was
dereferenced. This isn't _too_ surprising, as dereferencing the address
is one of the next things that's done after calling the swap() method.
Why the debugger zeroes out that part of the stack when you've got a
breakpoint set but not when you don't, I'm not entirely sure. But the
question is moot, as the code you've posted is code that should _never_ be
used.
It's unfortunate that in the nearly seven years that article has been on
the web, no one has bothered to comment on this flaw. It could definitely
lead to inexperienced programmers writing some really awful code. But,
hopefully now you at least understand why the code is wrong.
Pete