dynamic_cast throws unhandled exception during Reverse Polymorphism?

30 06 2008

What is Reverse Polymorphism?
Casting Base class object to derived class pointer is called Reverse Polymorphism or Inverse Polymorphism. Check the following code block.

// Base class.
class Base
    virtual ~Base() {}

// Derived class.
class Derived : public Base
    virtual ~Derived() {}

void CDialogDlg::OnButton4()
    // Base instance.
    Base* pBase = new Base;

    // Reverse Polymorphism. Cast Base Object to derived.
    Derived* pDerived = dynamic_cast<Derived*>( pBase );

While casting by using dynamic_cast, possible you may hit un-handled exception as follows.

Ideally dynamic_cast should return null, since its an invalid casting. But why its throwing un-handled exception? Is there something to do?

You’ve to enable RTTI. If RTTI is not enabled, it will throw un-handled exception for reverse polymorphism. For enabling RTTI,

1) Take project settings,
2) Take C/C++ tab.
3) In “C++ Language” category, enable RTTI. See the screenshot.

This is not a standard C++ behavior. This one is checked only in Visual C++ 6.0 compiler. You may or may not encounter the behavior in other Microsoft compiler version or in other compilers. So take care!

Targeted Audience – Intermediate.

How to generate the hash key of given data?

27 06 2008

Hashes are everywhere. Hash is small key generated from a bulk chunk of data. The hashes are useful in many ways. They are used for table lookups and data comparison. Yes! As you think now, hash table is one among them which utilizes hashes for high speed lookups. Well, thats a good, But how to generate the hash of a chunk of data?

You can use the function – HashData(). See the following code snippet.

#include "Shlwapi.h"
// Buffer for hash Key.
const int MAX_HASH_LEN = 256;
BYTE Hash[MAX_HASH_LEN] = {0};

// Chunk of Data.
char* pData = "Hello World";

// Generate Hash Key.
HashData( (LPBYTE) pData,
          strlen( pData),
          MAX_HASH_LEN );

Do you know that in real world, Hash means – “Chop and Mix”. Have a look at Wiki –

BTW, Don’t forget to add Shlwapi.lib to project settings. 🙂

Targeted Audience – Beginners.

Function call by using null pointer will crash?

26 06 2008

Crash on function call by using null pointer – The ultimate C++ Nirvana. 😉 Whether function call by null pointer always crash? Is it possible to call functions by using null pointer without crash? Check the following code snippet. Whether it will crash?

// Console Helper class.
class ConsoleHelper
    // Prints a line to console.
    void PrintLine()
        cout << "---------------" << endl;

// The one and only one Main.
int main(int argc, char* argv[])
    // Call the function by using null pointer.
    ConsoleHelper* pConsoleHelper = 0;

    return 0;

It won’t crash. Because in the function call we’re not accessing any member variables. Function call by using null pointers crash only if we’re accessing some member variables. Its because for every object function call, the object address is pushed to the function stack as “this” pointer. If the object pointer is null, then the “this” pointer also become null and hence the crash!

Null pointers are not that much bad! isn’t it? 😉

Targeted Audience – Intermediate.

Allocate CString on heap – Does that saves memory and improve performance?

24 06 2008

“Objects – The stack’s worst enemy. The stack is only indented for light weight datatypes such as int, float etc. So if you want to allocate a lot of objects, allocate on Heap. Or else stack will overflow”

This is the golden rules that beginners learn first, while stepping into professional C++ development. While considering objects, CString instances are the most common ones used in almost all MFC applications and for improving performance and for saving memory, usually we used to allocate it on heap. But, does that saves memory and improve performance? Well, its a myth. Want to know why?

First of all check the following code snippet and answer me, whether the message box will be shown or not?

// CString size == int size?
if( sizeof(CString) == sizeof(int))
    // I can't believe it.
    AfxMessageBox(_T("Am I dreaming?"));

Yes! It’ll be shown and the size of CString is just 4 bytes. Actually CString just contains LPTSTR as member. CString always allocate the string on heap. So while allocating CString itself on heap, you’re really degrading performance by extra heap allocation and more over you’ve to manage the pointer which can lead to memory leaks.

Don’t think that all objects are good candidates for heap. There can be exception like our CString. 😉

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 empty recycle bin programmatically?

21 06 2008

While processing or writing huge files to disk, its quite possible that disk will go out of space. To Squeeze and to get more disk space, its a good idea to clean the recycle bin. But how to do it programmatically?

You can use the api – SHEmptyRecycleBin(). See the code snippet below.

// Empty the recycle bin.
SHEmptyRecycleBin( NULL,
                   SHERB_NOCONFIRMATION |
                   SHERB_NOPROGRESSUI   |
                   SHERB_NOSOUND );

By modifying the options, you can show progress UI, Show confirmation dialog and play sound on finishing task. Just remove the unwanted flags.

Targeted Audience – Beginners.

How to list directories / files of a given path in your listbox easily?

19 06 2008

Assume you’ve a listbox and you want to fill all directories/files of a particular path to it. The usual method is iterate each file by FindFirstFile() and FindNextFile(), then add to listbox. Or any other cool tricks to do the same more easily?

You can use the api – DlgDirList(). It will populate the directories or files or drives to your listbox. You can select it by providing appropriate options. See the sample code snippet below, which lists all directories under C:\.

// The path Variable should be modifiable buffer.
// Since DlgDirList() returns data through it.
TCHAR Path[MAX_PATH] = _T("C:\\");
::DlgDirList( GetSafeHwnd(),
              Path, // in/out param.

For identifying directories, the DlgDirList() will decorate the directory name in format “[Directory]”. Now how to get the selected directory path from the listbox? Since its decorated, for that purpose, you can use function – DlgDirSelectEx(). It will undecorated the directory name and returns the real name. See the code snippet below.

// Read the selected directory from Listbox
TCHAR SelectedPath[MAX_PATH] = { 0 };
DlgDirSelectEx( GetSafeHwnd(),
                IDC_LIST1 );

Have a look at similar apis, such as DlgDirListComboBox(), DlgDirListComboBoxEx() etc. The name itself explains about it. Isn’t it? 😉

Targeted Audience – Intermediate.

How to find the size of dynamically allocated array?

18 06 2008

While passing dynamically allocated arrays to functions, we usually pass the pointer and size of array. Its because we cannot identify how many members are be present in the allocated array. It will be nice to find the size of array from the pointer itself so that we can eliminate that extra variable. But is it possible? Yes, you can find the size of array from pointer itself. But how?

You can use _msize(). If you give a pointer, it will return back the allocated size in bytes. See the sample code snippet below.

// Allocate some objects.
CRect* pRectArray = new CRect[50];
// Calculate the array size from pointer.
int ArraySize = _msize( pRectArray ) / sizeof( CRect );

Note that this is microsoft extension and is not the part of standard C++. Now throw away that extra size parameter from your functions. 😉

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 hook memory allocations?

16 06 2008

Memory allocation hooking is always handy. For instance, if you want to know whether the memory leak is due to the 3ed party dll calls, then hook the memory allocation and then call the 3ed party api. If the dll does some memory allocation, then your hook function will be triggered. So far so nice – But how to hook the memory allocations?

You can use the function – AfxSetAllocHook(). See the code snippet below.

// The hook function.
BOOL AFXAPI AllocHook( size_t nSize,
                       BOOL bObject,
                       LONG lRequestNumber )
    // bObject will be TRUE if the allocation
    // is a CObject derived class.
    return TRUE;

void SetHook()
    // Set the hook.
    AfxSetAllocHook( AllocHook );

    // Try some allocations.
    CDialog* pString = new CDialog;
    int* integer = new int;

The bObject flag will be true if the allocation is for a CObject derived class.

AfxSetAllocHook() is only available in debug version. So take care!

Targeted Audience – Intermediate.