Debugging program shows different value once breakpoints are added

T

Tim Sprout

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 am using Visual Studio Express 2008, compiling to DotNet 2.0.

Thanks,

Tim Sprout



class MyClass
{
public unsafe void Method()
{
int x = 10;
int y = 20;
int *sum = swap(&x, &y);
MessageBox.Show(" Value at Memory Address = " + *sum);
}
public unsafe int* swap(int* x, int* y)
{
int sum;
sum = *x + *y;
return ∑
}
}

private void btnDisplayMessage2_Click(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.Method();
}
 
T

Tim Sprout

Peter said:
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

Thanks for your explanation, Pete.

Tim Sprout
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top