Tuesday, July 31, 2007

RichEdit Common Mistake MFC Win32

 If you ever tried RichEdit control in Vc++ , may be at first use you will notice that your application may crash , or the dialog is not coming.  The problem is , the RichEdit module is not loaded to memory initially. We need to load it explicitly. IF you are using MFC there are functions like
AfxInitRichEdit2(); // RichEdit Version 2
and
AfxInitRichEdit();  // RichEdit version 1.
If you are doing pure win32 , just by loading the richedit2.dll to meory will solve the problems , like
LoadLibrary("c:\\WINDOWS\\system32\\riched20.dll"); // this is richedit version 2.also remember to unload the module with FreeLibrary function.
You need to call the approrpiate function (AfxInitRichEdit or LoadLibrary) before creating richedit. The best way is to call is  in the InitInstance in MFC , or winmain Win32.

Thursday, July 26, 2007

Empty class size c++

People may thinks like the size is zero for an empty class (Me also thought
i
n the beginning). But it is not true. The size of an empty class will be never
zero. It is nonzero. There are two reasons for that.

1) the sizeof operator in c++ never returns zero.
2) IF the size becomes zero it may cause to have some invalid address
arithmetic operations.

so the size of an empty class is never zero , it is always nonzero (and this
value depends on compiler).

Friday, July 6, 2007

Placement New


This is not a new subject. Many of us knows this. Many not knows.
Placement new means we can ask the new operator to allocate from a particular memory area. This can be useful when implementing memory pools , to avoid fragmentation of memory.

This is the way to do this.

// Our mem pool of size 1000 bytes.
unsigend char *pMemPool = new unsigned char [1000]; // 1000 bytes is a sample ,use large numbers here.

Now i can ask new to allocate to pMemPool like this

Someclass *p = new (pMemPool) new Someclass;

When comparing the p and (Someclass *) pMemPool reveals they are equal. Don't free p, it will delete whole memory pool ( pMemPool). So allocate as much possible to this memory pool, later we can delete the whole pool . This helps to avoid memory fragmentation.