Gold mine of Visual C++ tricks!
Memset on objects will result in crash? Then none of your MFC apps will work.
![]()
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.
![]()
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!
| Print article | This entry was posted by Jijo Raj on March 25, 2008 at 6:36 pm, and is filed under Codeproject, MFC. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |










about 2 years ago
Congrats on finding the courage to dig into
raw MFC code… Gotta love MFC !
Slight point of critique: Maybe it makes sense also to mention
how to properly initialize objects ?
about 1 year ago
thank you.
about 1 year ago
Always Welcome.
Keep watching buddy.
Regards,
Jijo.