How to Watch Variables in Binary by using Visual Studio Debugger?

1 01 2009

In visual studio you can watch variable values in different formats. For instance, for viewing in hex add this to watch window – var,x and for octal – var,o. But its a pity that visual studio doesn’t support displaying variables in binaries. So how can you watch the value of a variable in binary, with debugger? 😉

Image Courtesy – Pixdaus.

Well, we have to utilize the special feature of visual studio debugger. Basically the watch window is not just a tool to display the variable value. It can evaluate and execute small code snippets as well. If you add a function call to the watch window, that function will be called when debugger refreshes the watch values. So, all you have to do is – Add a global function which accepts integer value, converts it to binary string then display it to output window. Have a look at the function.

// Global function which converts integer to binary
// and dump to the output window.
void DumpBinary( DWORD Value )
    // Buffer to hold the converted string.
    TCHAR Buffer[255] = { 0 };

    // Convert the value to binary string.
    _itot( Value, Buffer, 2 );

    // Display to output window.
    CString csMessage;
    csMessage.Format( _T("\n%d in binary: %s"), Value, Buffer );
    OutputDebugString( csMessage );

Now if you want to convert the 100 to binary, break at some location and just add DumpBinary(100) to watch window and check the output in the output window. See the screenshot below.


Just now I realized – how powerful the Visual Studio Debugger is. Hats off to Visual Studio Team!

Well, please note that in visual studio 2008 and may be in siblings, When you add this to watch window, its possible to see this error – “CXX0001: Error: error attempting to execute user function”. In that case just click the “Evaluate button” which appears next to it and the expression will be re-evaluate.

Targeted Audiance – Advanced.

How to Debug the Release Build?

16 11 2008

“Debugging in release build!!! Is it possible?” I’ve heard this questions a couple of time, especially from Visual C++ Novices. Yes! its possible. But why?
I still remember my first project. We did everything right, debugged and fixed all bugs in debug build and released the application. But client tested the release version and it was like FatMan, a lot of crashes.

So, Debugging in release build is important because, even though the debug build can catch most of issues, there might be some bugs or crashes still hiding under the release version of application. For catching them, there is now way other than to debug the release build itself.


Well, basically compiler needs debug information for stepping into code while debugging and In release build, by default there will not be any debug information. Compilers cannot interpret or understand optimized code and in release build, optimization will be enabled by default. For debugging in release build, you’ve to generate debug information and to turn off optimizations. Follow the steps about how to tweak project settings for that.

1) Take project settings by Alt+F7.
2) Select Release configuration.
3) Select “C/C++” tab. Set “Optimizations” as “Disable Debug” and “Debug Info” as “Program Database”.


4) Take “Link” tab. Enable “Generate Debug Info“.


5) Now from menu, take – “Build > Set active configuration…” and select Release build as default.


6) Rebuild the project by F7.
7) Now what are you waiting for? Press F5 to debug and enjoy!

Since my first project, I don’t forget how to debug in release version. 😀 and this is my advice for you – “Its fine to do the entire debugging in debug build, because its tuned to catch a lot of bugs. But before releasing check the release build too.”

Targeted Audience – Beginners.

Be careful while watching variables with Visual Studio Debugger’s tooltip.

17 07 2008

We used to watch variables values by hovering mouse over them. So visual studio will show the variable value as tooltip. But beware, pitfalls are waiting for you, especially while watching structures.

If you just hover the mouse over a variable, Visual Studio will pick the variable name just below and shows its value as tooltip. But it can be dangerous. For instance, assume you’ve a structure, and local variable with name same as structure member. Check the code snippet.

// Some structure.
struct Drive
    BOOL Present;

void Function()
    // Local variable with same name
    // as structure member.
    BOOL Present = FALSE;

    // Structure with variable
    Drive CdDrive = { 0 };

    // If you watch the var by mouse hover,
    // the value displayed will be that of
    // local variable.
    CdDrive.Present = TRUE;

If you just mouse hover on the structure member variable, you’re going to deep trouble. The value displayed will be wrong. Since debugger choose just the variable name under the mouse, if a local variable of same name exists, the value of local variable will be displayed. Enough and more to get mis-guided. Have a look at the screenshot.

So always watch structure members by selecting the full variable name. See following screenshot.

Silly stuff. But it can grab a lot of time by blaming the compiler and rebuilding source again and again as I did. 😉

Targeted Audience – Intermediate.

How to watch a range of values inside huge array?

3 07 2008

Assume you’ve an array with 1000 elements in it and you want to watch elements from 500 ~ 510, what will you do? One method is you can watch the array directly which will list all the 1000 variables and you’ve to scroll up to 500th element and have to watch. Is there any trick to watch just the range of 10 elements between 500 to 510?

Yes! Basically the idea is, you’ve to add – (Array+RangeStart)+RangeCount to the watch window. But there are different scenarios and obviously the trick varies slightly. See examples below.

1) If you have dynamically allocated array.
Check the code snippet.

// Array ptr with 1000 elements.
int* pArray = new int[1000];

// Initialize range 500 to 509 as 1.
for( int ArrayIndex = 500; ArrayIndex < 510; ++ArrayIndex )
    pArray[ ArrayIndex ] = 1;

In this case for watching range 500 ~ 510, you’ve to add – (pArray+500),10 to watch window. See the screenshot.

2) If you have array on stack.
If you’re array is on stack, if you add your array to watch window, the debugger automatically expands all elements, since it knows the max size of array. But we just want to see the range. See the code snippet.

// Array with 1000 elements.
int Array[1000] = { 0 };

// Initialize range 500 to 509 as 1.
for( int ArrayIndex = 500; ArrayIndex < 510; ++ArrayIndex )
    Array[ ArrayIndex ] = 1;

In this case for watching range 500 ~ 510, you’ve to add – ((int*)Array+500),10 to watch window. See the screenshot.

Watch window is a Treasure chest! isn’t it? 😉

Targeted Audience – Intermediate.

How to watch vectors more easily?

23 06 2008

Everyone uses vectors and during debugging if we’ve to watch the elements, its a real headache. The usual method that follows is to quick watch the vector and we add index to the _First element. For instance, assume we’ve the vector generated by following code snippet.

// The String Vector.
vector<CString> StringVector;

// Add some strings to it.

For watching it, we quick watch and click the _First member of vector and adds an index to it to skip to the nth element. See the screenshot.

Is there any better way to watch the whole vector instead of this iteration?

Yes! you can. First you’ve to get the vector size by adding “StringVector.size()” to watch window. Then you’ll get the size. Now add “StringVector._First,size” to the watch window. That will show all the elements in that vector. Just see the screenshot.

You can evaluate the same expression in your quick watch window. Have fun!

Targeted Audience – Intermediate.

How to detect Memory Leaks by using CRT?

17 06 2008

Memory leaks are every programmers nightmare. Usually we used to use memory leak detection tools such as Numega BoundsChecker, Rational Purify to find memory leaks. But do you know that our C Runtime library have pretty good support for isolating memory leaks?

You’ve to enable memory leak tracking by defining constant – _CRTDBG_MAP_ALLOC and then call – _CrtDumpMemoryLeaks(). Now the leaks will be dumped to the Visual Studio output window. See the following code snippet.

// Declare this in header.
#include <crtdbg.h>
void DetectLeaks()
    // Create some leaks.
    CString* pString = new CString;
    BYTE* pBuffer = new BYTE[100];

    // Dump memory leaks to output window.

When you call _CrtDumpMemoryLeaks() the memory leak information will be dumped to the output window. For instance, see the dump for memory leaks that we’ve made in DetectLeaks().

Detected memory leaks!
Dumping objects ->
C:\Jijo\Studies\VC++\MFC\RabbitDlg\RabbitDlgDlg.cpp(183) : {194} normal block at 0x00294990, 100 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
C:\Jijo\Studies\VC++\MFC\RabbitDlg\RabbitDlgDlg.cpp(182) : {193} normal block at 0x00293B20, 4 bytes long.
 Data: <   _> 14 FB 8C 5F
Object dump complete.

The filename and line number of leak will be present in the dump. So easy, nah?

While creating your MFC applications, did you ever noticed a code block as follows in your files?

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;

This is for debug information. By using this information, the _CrtDumpMemoryLeaks() keep track of the filename. If you comment out this, the filename will not be present in the dump which will make our task difficult. So never remove those line. I swear, they are really important! 😉

Targeted Audience – Intermediate

How to enable/disable all breakpoints in single keystroke?

9 06 2008

During heavy debugging, we usually have dozens of breakpoints dropped in various locations of source. Some of these breakpoints can also be in the application startup route. While stopping and starting programs during debugging, these breakpoints are really irritating, because they stop always. I’ve to press F5 a couple to times to start the application and run it. If there’s some shortcuts to enable and disable all break points at one single keystroke, it will be nice. isn’t it? But how?

You can use the VisualStudio’s powerful object model to do so. See the macro code for enabling and disabling the breakpoints. In later steps, i’ll explain how to map it to keystroke. The macro code is as follows,

' Macro to Enable all Breakpoints.
Sub EnableBreakPoints()
    Dim myBreakpoint
    For Each myBreakpoint in Debugger.Breakpoints
        ' Enable the break points.
End Sub

' Macro to Disable all Breakpoints.
Sub DisableBreakPoints()
    Dim myBreakpoint
    For Each myBreakpoint in Debugger.Breakpoints
        ' Disable the break points.
End Sub

How to map the macros to Keystroke
1) Take Tools > Macro.
2) Now you’ll see your macro window and i assume no macros are defined in your macro file. For getting the macro editor, enter some dummy macro name and click “edit” button.

3) Now Macro editor will be opened and copy-paste the Enable/Disable macro code in your macro editor and save it.
4) Now take Tools > Macro again and VisualStudio will ask, whether to reload the macros. Press Yes.
5) Now you’ll see the macro dialog, and click “Options” and “Keystrokes“.

6) Now select the macro and press a key combination, then click “Assign”.

7) The greatest difficult that you’ll face is to find a free slot of key combination. Almost all are reserved by visual studio itself. 🙂 After some R&D I’ve found two working key combinationAlt+z and Alt+x. Map your enable/disable macros to those shortcuts.

8 ) Now take visual studio and press the key combination to disable the breakpoints. Note that the breakpoints will not be visually disabled but if you take breakpoint window by Ctrl+B you can see all are disabled. This happens because we’ve modified the internal structure of VisualStudio, but GUI is not refreshed.

The only drawback is the breakpoints will not be visually disabled on keystroke. I’m searching for some solution and hope i’ll be back soon. Till then enjoy this one. 😉

Targeted Audience – Intermediate.