Trailing spaces after backslash delimiter – Programmers nightmare.

31 03 2008

Icon Description
Usually we used to have spaces after semi columns. Since C++ ignore whitespace, its not a problem. But in Visual C++ 6.0 that is not the case always. If you put spaces after the backslash delimiter(\), it will become one of the worst bugs that you encounter.

Usually we use backslash delimiter to concatenate lines – mostly while writing macros. See the following macro.

    Value = Value + 1; \ » » »
    Value = Value - 1;

In the macro, instead of » char, put some tab or space and then compile. You will get a strange error as follows.

error C2501: 'Value' : missing storage-class or type specifiers

Icon How Can I Do It?
One of the defensive mechanism is – always enable “View whitespace” by pressing Ctrl+Shift+8. So take care next time and don’t spend hrs on these silly bugs as I did years before.

Note that its just a implementation behavior in Visual C++ 6.0 and may not found in other compilers or upcoming Visual C++ versions.

Thanks to Hemant for pointing out my implicit biasing towards VisualStudio 6.0. I forgot to specify that its just a Visual studio behavior.

Targeted Audience – Intermediate.

Visual C++ Preprocessor null directive

30 03 2008

Icon Description
Well, add an empty # symbol to your #include list and compile the project. For e.g. see the following #include list.

#include “stdafx.h”
#include “Dialog.h”

#include “DialogDlg.h”

It will compile without showing any errors. Weird?

The single “#” in a line is called null directive. It has no effect. Indeed, its not a bug. 😉
But i can’t find the answer for question… What is the purpose?

Reduce iostream compilation dependency by using iosfwd

30 03 2008

Icon Description
For making our classes compatible with cin and cout, we usually over load << and >> operators. And if such classes are the part of our modules interface, the iostream header file should be added to the interface header of our module. It makes compilation overhead for the classes those use our exported class. Please see the following code block.

#include <iostream>

class IMyInterface
    // Overloaded << operator.
    std::ostream& operator<<( std::ostream& os );

Icon How Can I Do It?
You can easily reduce the compile time dependency of iostream header by using iosfwd. It contains forward declaration of several template classes defined in iostream. Please check MSDN for more details. Don’t forget to include iostream in your cpp files, since iosfwd contains just forward declarations.

#include <iosfwd>

class IMyInterface
    // Overloaded << operator.
    std::ostream& operator<<( std::ostream& os );

List the loaded modules in your crash report.

29 03 2008

In crash reports, usually we see a list of loaded modules. While writing Error Handler frameworks, for dumping crash reports we too need to get list of loaded modules which will make the debugging tasks easier. But how can we find out the loaded modules? You can use EnumerateLoadedModules() function to enumerate the loaded modules.

You can use EnumerateLoadedModules() function to enumerate the loaded modules. For calling EnumerateLoadedModules() we need provided a callback function pointer. The EnumerateLoadedModules() will send the loaded module information as callback to that provided function. Please see the following code

#include <Dbghelp.h>  

// Callback function.
BOOL CALLBACK EnumerateLoadedModulesProc( PSTR ModuleName,
                                          ULONG ModuleBase,
                                          ULONG ModuleSize,
                                          PVOID UserContext )
    // Print the module name.
    cout << ModuleName << endl;
    return TRUE;

int main(int argc, char* argv[])
    // Enumerate loaded modules.
       GetCurrentProcess(),	// Process Handle
       // Callback function pointer
       (PENUMLOADED_MODULES_CALLBACK) EnumerateLoadedModulesProc,
       0 );	// User context.   

       return 0;

Add beauty and complexity to your crash report by listing out the module names 😉

How to remove unwanted libraries from project settings.

28 03 2008

Icon Description
Usually in the project settings, we will provide a list of .lib files that the project needs to compile. For small projects it’s manageable. But for big project which uses a lot of 3ed party frameworks, the .lib list can grow and may contain unwanted libraries which are not used any more. Even though an extra library in project setting is harmless, it may end up messing up the project setting. Some clients even have strict project setting rule – project settings should not include unused libraries.

Icon How Can I Do It?
One method is error and trial. Remove each library by hand and compile. If you won’t get any error then you can remove it. Or else you should try Masters Method!

1) Take project settings.
2) Take Link tab.
3) In the “project options” editbox add the switch – /verbose
4) Rebuild the project
5) Now in the output window you can see a lot of messages other than normal build.
6) Find the pass 2 section in the output messages. It will be almost same as follows

Start Pass2
End Pass2

7) In the pass 2 section, linker will emit all used libraries.
8 ) In the above e.g. the lib files needed
are “kernel32.lib” and “LIBCD.lib”
9) So you’ve found the required library files!
10) Add them to “object/library modules:” editbox of linker settings.
11) Don’t forget to enable “ignore default libraries” options of linker. Because by default the linker links a set of default libs to the project. Those libs are no more needed!
12) Your project is free from unwanted libraries.

Now the choice is yours.Want to go for “Error and trial” or “Masters Method”? 😉

Targeted Audience – Advanced.

GetCurrentThread() returns pseudo handle, not the real handle.

26 03 2008

Icon Description
For getting our thread handle, we usually call GetCurrentThread() api. But actually it returns a pseudo handle. A pseudo handle, is a special handle which represents the handle of current thread which uses it. Please see the following e.g. for more clarify.

1) Thread A gets its threadID by calling GetCurrentThread and Passed to Thread B.
2) Thread B needs to terminate Thread A. So it calls TerminateThread( handle passed by Thread A ).
3) But instead of terminating Thread A, Thread B will be terminated, because the handle passed by Thread A was pseudo and it will become Thread B’s handle when Thread B uses it.

Debug one GetCurrentThread() call and GetCurrentProcess() call and watch its return values. You can see what they returns are follows,

  • GetCurrentThread() – 0xfffffffe
  • GetCurrentProcess() – 0xffffffff

Ofcourse pseudo… isn’t it ?

Icon How Can I Do It?
For getting a real handle which represents your thread, create a duplicate handle by calling DuplicateHandle(). Please see the code block below.

HANDLE hRealHandle = 0;
DuplicateHandle( GetCurrentProcess(), // Source Process Handle.
                 GetCurrentThread(),  // Source Handle to dup.
                 GetCurrentProcess(), // Target Process Handle.
                 &hRealHandle,        // Target Handle pointer.
                 0,                   // Options flag.
                 TRUE,                // Inheritable flag
                 DUPLICATE_SAME_ACCESS );// Options
// Now the hRealHandle contains a real handle for your thread.

How to skip a class or library from being profiled?

26 03 2008

Icon Description
We used to run profiler for performance tuning. By using profiler, you can check – function timing, function coverage etc. By default profiler profiles the entire modules. But how can we skip a particular user library or class from profiling?

Icon How Can I Do It?
There is a setting file named profile.ini, where profiler keep its settings.
For skipping a user library just add a line like this.

Assume you have a class named CHighPerfomance and want it to be skipped from profiling, then add the following line.

Icon - Where is it?
The profiler setting file is located at

Memset on objects will result in crash? Then none of your MFC apps will work.

25 03 2008

Icon Description
While stepping from C to the C++ world, it’s the first pitfall that we encounter – initializing an object with memset. Since memset if faster, we used to initialize objects like this,

CObject obj;
memset( &obj, 0, sizeof(obj));

More than enough for a crash! Because if the class contains virtual functions, then the first 4 bytes holds the pointer to vtable. If we use memset, then the vtable pointer will be overwritten to 0 and it may end up in crash.

But, do you know one thing? The famous MFC framework uses memset to initialize some of its objects such as CDialog, CScrollView etc. Can’t believe? It does, but safely. Without damaging the vtable pointer.

If you check the constructor of CDialog, you can see one macro – AFX_ZERO_INIT_OBJECT();. This macro calls memset internally. See the implementation of macro below.

// zero fill everything after the vtbl pointer
#define AFX_ZERO_INIT_OBJECT(base_class) \
memset(((base_class*)this)+1, 0, sizeof(*this) - sizeof(class base_class));

But it’s safe. Because it skips the vtable ptr.

Icon Note
Don’t try this macro in your source. Because CDialog doesn’t contain any objects as members. It contains just some pointers and handles. If your object contain some class variables as members which contain virtual table, then that vtable ptr may be overwritten. Take care!

Trigraph char sequences in C & C++

25 03 2008

Icon Description
There are some triplet character sequences present in C & C++ to represent some special punctuation characters. The trigraph sequences are used for compatibility of source code written in ISO 646 or EBCDIC charset.

// Is this a valid statement? I can’t believe. But for compiler is valid.
??=define arraycheck(a,b) a??(b??) ??!??! b??(a??)

But when we apply trigraph sequence, the above code block became as follows.
// Wow!!! It’s a valid one…
#define arraycheck(a,b) a[b] || b[a]

Please see list of trigraph sequences below.
Trigraph Punctuation Character

??=	            #
??(                 [
??/                 \
??)                 ]
??’	            ^
??<                 {
??! 	            |
??>	            }
??- 	            ~

And one trigraph pitfall.
// Whether the following line compiles ???????/
cout << “Whether you can see this message?”;

Find your answer and take care trigraphs next time…
Thanks to Wiki for examples and the list.

Watch heap objects eventhough the symbol went out of scope.

25 03 2008

Icon Description
While debugging we want to watch some objects through out. An object can be watched only with its symbol and it should be valid in the current stack frame. For instance,

CJobManager* CJobManager::GetJobManager
    return m_pJobManager;

For watching the JobManager instance, we need the symbol m_JobManager in this stack frame. When the function leaves, we can’t see the JobManager instance anymore. So how can i watch these heap objects without the symbol in stack frame?

Icon How Can I Do It?
1) Get the address of your heap object. Just add to watch window and get the location. For instance assume its 0x00034de0.
2) Now add a new entry to the watch window like this – (CJobManager*)(0x00034de0)
3) Now eventhough your function returns and you loss the symbol, still you can see your heap object.

Really helpful isn’t it? i was fed up with the global objects in my project and atlast find this method to watch them premenently.