9

I have program that has a variable that should never change. However, somehow, it is being changed. Is there a way to have the debugger stop when that particular member variable is modified?

max
  • 1,020
  • 1
  • 15
  • 25

3 Answers3

11

Set a data breakpoint to stop execution whenever some variable changes.

Break on the initialization of your variable, or someplace where your variable is visible - you need to be able get its address in memory. Then, from the menus choose Debug -> New Breakpoint -> New Data Breakpoint. Enter "&var" (with var replaced by the name of your variable.)

This will break into the debugger on the exact line of code that is modifying your variable.

More documentation here:

http://msdn.microsoft.com/en-us/library/350dyxd0.aspx

Charlie
  • 1,598
  • 1
  • 8
  • 11
  • For sake of completeness: there may be other things changing a value than your code, and those things are not captured by a memory breakpoint: http://stackoverflow.com/questions/2362688/global-variable-is-changed-but-memory-breakpoint-is-not-hit – Suma Feb 10 '11 at 14:18
2

You can set conditional breakpooint at places where the variable is used.

In Visual Studio set breakpoint by pressing F9 when your cursor at the line where you want to set breakpoint.
Next, right click on the breakpoint and select Condition.
Type your condition like

n != 5

Good luck.

Here's a link from MSDN.

Vadim
  • 21,044
  • 18
  • 65
  • 101
0

If it is being modified through an assignment or other direct update, the data breakpoint will work. However, if it is being modified via some other means - for example a buffer overwrite - I'm not sure if it will tell you exactly when it occurs. Just something to keep in mind.

sean e
  • 11,792
  • 3
  • 44
  • 56
  • 1
    Unless I'm seriously mistaken, a data breakpoint is set on the *memory location* and not the identifier. (That's why you have to give an expression that evaluates to an address when you set one.) So it should catch buffer overflows, smashed stack, heap corruption, and all that good stuff. – Charlie May 16 '09 at 03:58
  • That sounds right. I guess the issue I'm thinking of is when an identifier name is optimized away and you aren't able to even set the breakpoint. – sean e May 16 '09 at 15:58
  • Don't worry, it's a hardware feature, seriously. – rama-jka toti May 16 '09 at 23:23