Visual Studio Debugger: Break When Expression has Changed

One of the lesser known features of the Visual Studio debugger is the ability to break when a variable or range of memory has changed. In a nutshell, the debugger checks the variable or the range of memory as each line or each instruction is executed. When a change is detected, the debugger breaks. This type of breakpoint is known as a Data breakpoint (as in break when data has changed) The key difference between a Data breakpoint and other types of breakpoint is that a Data breakpoint doesn't specify a location to break at.

Example: Break when a variable has changed

In the following example, to have the debugger break when the variable remainder has changed, the first step is to stop somewhere in the application using the debugger. This may seem unintuitive at first, but since a Data breakpoint breaks on a memory location, the application must first be running. In fact, the command to set a Data breakpoint is unavailable until the application is in break mode.

   1: /*
   2: * Prints out whether an integer is even or odd.
   3: */
   4: void main()
   5: {
   6:     int number;
   7:     int remainder;
   9:     printf("Enter number: ");
  10:     scanf_s("%i", &number);
  12:     remainder = number % 2;
  14:     if (remainder == 0)
  15:         printf("Number is even\n");
  16:     else
  17:         printf("Number is odd\n");
  18: }

Once you are stopped in the debugger, you can bring up the Data Breakpoint dialog by going to Debug->New Breakpoint->New Data Breakpoint.

New Data Breakpoint Menu

In the New Breakpoint dialog, enter &remainder in the Address textbox and press [OK]. Notice that I used the "address operator" (&) to specify the memory location of the variable remainder.

Data Breakpoint dialog

When you set the breakpoint, notice that it doesn’t appear in the margin of the source code window. However, you can see the breakpoint in the Breakpoints window.

 Breakpoints dialog

When the debugger executes line 12 above, i.e. remainder = number % 2, the memory location that holds the value of the remainder variable is changed. At that point, the debugger displays the following dialog. After pressing the [OK] button, the debugger will break at line 12.

Data Breakpoint triggered dialog

One thing to note is that the variable that you want to set a data breakpoint on must be declared before you can set a Data breakpoint. Also, Data breakpoints are only available for unmanaged code, i.e. C/C++.

Habib Heydarian.

Comments (1)

  1. Thank you for submitting this cool story – Trackback from DotNetShoutout

Skip to main content