Break when a value changes using the Visual Studio debugger
Asked Answered
M

14

238

Is there a way to place a watch on variable and only have Visual Studio break when that value changes?

It would make it so much easier to find tricky state issues.

Can this be done?

Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes.

Mazman answered 1/10, 2008 at 22:26 Comment(5)
but the breakpoint doesn't affect anything unless the condition holds, so you can put your breakpoint anywhere (like the Setter) and take it from there. Or am I missing something?Restorative
well. its like the vb6 way of debugging. you dont care about the breakpoint location. just add a conditional expression to watch window and vb6 will gurantee it will break wherever the condition is met..Fayina
sorry, never seen a way, as far as I know the setter is the way to goRestorative
i was hoping to find better news; the vs2010 indicates no change msdn.microsoft.com/en-us/library/350dyxd0.aspx only native c++ has this @Scottgu you can do better!Approve
This question is not very clear what language is being asked about. That makes a big difference in terms of what features are relevant and available.Allantoid
M
152

In the Visual Studio 2005 menu:

Debug -> New Breakpoint -> New Data Breakpoint

Enter:

&myVariable
Marilou answered 1/10, 2008 at 22:36 Comment(10)
is this available for managed code? I see this option disabled for C# project. Remember reading somewhere this is a tough feature to implement in debugging managed apps especially with garbage collector involved.Fayina
It's only available for unmanaged code, unfortunately: msdn.microsoft.com/en-us/library/350dyxd0.aspxDither
I think you still needs to put a breakpoint if your data is not global. VS replaces the &var by the memory address, it doesn't remember accross runs that you would like to stop on this variable.Jamey
You can also temporarily convert a field to a property and put a breakpoint on the getter or setter.Autrey
@stimpy77 -- only works for properties that have setters (i.e. calculated properites won't work) -- also this implies that you have the source code to the object that's acting weird -- In that case, of course that's what you'd do! -- But if someone's looking for this feature in VisualStudio, I'd guess they were beyond that point (like I currently am).Intellectualize
The "Data Breakpoint" option under "Debug -> New Breakpoint" is disabled.. any idea why? It stays disabled wether or not I'm actually debugging or not. I'm using Visual Studio 2015.Modie
A little late but @Modie for me it is only enabled when I'm stopped at a break point while debugging.Staffer
Very, very useful feature in vs2017. I simply put the hex address of the variable I like to monitor, (and the size, usually 4 for DWORD). And voila!! I discovered where in my giant forest of C++ codebase tried to set the value!!! A miracle!!Anorthic
How can you use this for an STL value's raw value. For example say I wanna break when a std::string's actual C-string is modified. &mystring won't work because this will only break if the address of the C pointer changes or something like capacity or size. If you try mystring.c_str() Visual Studio won't let you, claiming the expression has side effects i.e. "This expression has side effects and will not be evaluated".Tracey
For managed code, Data Breakpoints are only possible since Visual Studio 2019 but only for .Net Core (3.0 or higher). See the answer re Visual Studio 2019 and vote it up.Takao
G
33

You can also choose to break explicitly in code:

// Assuming C#
if (condition)
{
    System.Diagnostics.Debugger.Break();
}

From MSDN:

Debugger.Break: If no debugger is attached, users are asked if they want to attach a debugger. If yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit.

This is only a fallback, though. Setting a conditional breakpoint in Visual Studio, as described in other comments, is a better choice.

Glia answered 1/10, 2008 at 22:45 Comment(2)
FWIW, with edit and continue I prefer doing it this way: IME, conditional breakpoints are sloooowNewcomen
This works -- but it's very painful -- I ended up doing something similar -- I put this at the top of every method I suspected -- and again at the bottom (in a finally clause) -- that way I knew exactly which method was causing the problem -- (i.e. I knew the data was good before entering the method, and then bad before exiting it).Intellectualize
U
33

In Visual Studio 2015, you can place a breakpoint on the set accessor of an Auto-Implemented Property and the debugger will break when the property is updated

public bool IsUpdated
{
    get;
    set;    //set breakpoint on this line
}

Update

Alternatively; @AbdulRaufMujahid has pointed out in the comments that if the auto implemented property is on a single line, you can position your cursor at the get; or set; and hit F9 and a breakpoint will be placed accordingly. Nice!

public bool IsUpdated { get; set; }
Ur answered 16/6, 2016 at 21:31 Comment(2)
Even if auto implemented property is in one line e.g. public string UserName { set; get; }. User can highlight getter or setter and can press F9 to add breakpointRebak
@AbdulRaufMujahid Awesome!Ur
S
15

Imagine you have a class called A with the following declaration.

class A  
{  
    public:  
        A();

    private:
        int m_value;
};

You want the program to stop when someone modifies the value of "m_value".

Go to the class definition and put a breakpoint in the constructor of A.

A::A()
{
    ... // set breakpoint here
}

Once we stopped the program:

Debug -> New Breakpoint -> New Data Breakpoint ...

Address: &(this->m_value)
Byte Count: 4 (Because int has 4 bytes)

Now, we can resume the program. The debugger will stop when the value is changed.

You can do the same with inherited classes or compound classes.

class B
{
   private:
       A m_a;
};

Address: &(this->m_a.m_value)

If you don't know the number of bytes of the variable you want to inspect, you can use the sizeof operator.

For example:

// to know the size of the word processor,  
// if you want to inspect a pointer.
int wordTam = sizeof (void* ); 

If you look at the "Call stack" you can see the function that changed the value of the variable.

Susette answered 5/3, 2011 at 20:50 Comment(2)
So, what exactly would you do if the thing I'm looking for isn't in my own classes? Like, for example, I'm trying to find out exactly where a control gets enabled or disabled? I can add a watch on the control's Enabled value during debugging, sure, but there's no way to make it break on change and then look where it stopped.Terisateriyaki
If you try to debug a external library, you would need the library compiled in debug mode. I'm not familiarized with component, but maybe you can connect a "callback" to the property and put a breakpoint inside. The form that I describe needs the memory address, if you have no way of know it, there is to search other methods.Susette
S
11

Change the variable into a property and add a breakpoint in the set method. Example:

private bool m_Var = false;
protected bool var
{
    get { 
        return m_var;
    }

    set { 
        m_var = value;
    }
}
Selle answered 4/9, 2013 at 14:35 Comment(0)
C
5

Update in 2019:

This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.

https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/

Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!

Clangor answered 12/2, 2019 at 19:21 Comment(0)
S
4

If you are using WPF, there is an awesome tool : WPF Inspector.
It attaches itself to a WPF app and display the full tree of controls with the all properties, an it allows you (amongst other things) to break on any property change.

But sadly I didn't find any tool that would allow you to do the same with ANY property or variable.

Skirret answered 17/11, 2011 at 17:14 Comment(0)
F
3

I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.

Fayina answered 1/10, 2008 at 22:28 Comment(0)
R
2

Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).

Restorative answered 1/10, 2008 at 22:28 Comment(0)
D
2

As Peter Mortensen wrote:

In the Visual Studio 2005 menu:

Debug -> New Breakpoint -> New Data Breakpoint

Enter: &myVariable

Additional information:

Obviously, the system must know which address in memory to watch. So - set a normal breakpoint to the initialisation of myVariable (or myClass.m_Variable) - run the system and wait till it stops at that breakpoint. - Now the Menu entry is enabled, and you can watch the variable by entering &myVariable, or the instance by entering &myClass.m_Variable. Now the addresses are well defined.

Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.

Dreadful answered 14/1, 2019 at 11:6 Comment(0)
A
1

You can use a memory watchpoint in unmanaged code. Not sure if these are available in managed code though.

Arachnoid answered 1/10, 2008 at 22:38 Comment(0)
A
1

You can probably make a clever use of the DebugBreak() function.

Atmometer answered 18/5, 2011 at 6:52 Comment(2)
How exactly? By running a separate thread in a tight loop and invoking DebugBreak() whenever a change has been encountered?Erb
@nalpy You could for example trace the places where myVariable is used and store its values after use in a auxiliary previousValue variable, then call DebugBreak() when myVariable!=previousValue; then you would know between which code blocks myVariable has changed. But I agree that AShelly's solution is best.Atmometer
I
1

You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.

Illimitable answered 1/12, 2015 at 12:39 Comment(0)
L
0

You can place a breakpoint where you want than hover a mouse over it, click "settings"enter image description here

There you can add conditions, including curtain value changes: enter image description here

After conditions are set, the breakpoint will get "+" in icon. You also can move this conditions by dragging it

Laryngoscope answered 1/11, 2023 at 13:51 Comment(1)
This doesn't answer question at all. The problem is breaking on value change in any place of variable scope, not only where breakpoint is set.Musket

© 2022 - 2024 — McMap. All rights reserved.