Careful with memset and ZeroMemory!

Do not use these functions for initializing classes which contains other class objects. Always go via constructors for initializing class objects.

I personally use { 0 } for initializing c-style structures which is safe since compiler will give an error just in case future someone adds a class object to this structure. For e.g.

[sourcecode language=’cpp’]struct SampleStruct
{
char MyName[MAX_PATH];
};

// Using standard C++ initialization technique
SampleStruct SSObj = { 0 }; // Fine with the compiler, I like this way

// Using memset
memset( &SSObj, 0 , sizeof( SSObj )); // Initialize to zero, fine with the compiler[/sourcecode]

Now imagine this situation after sometime, someone re-factors above array to string class…

[sourcecode language=’cpp’]struct SampleStruct
{
string MyName;
};

// Using standard C++ initialization technique
SampleStruct SSObj = { 0 }; // Compilation error, and this helps

// Using memset, Initialize to zero, fine with the compiler, but inviting crash!
memset( &SSObj, 0 , sizeof( SSObj ));[/sourcecode]

I read in a blog sometime back that this technique( {0} ) reduces code readability, well I am yet to face a code readability issue!

The problem with my approach you can only initialize it where you declare it, this will be an issue when you have a structure member, so in that case use memset/ZeroMemory but keep in mind the problems!

For plain C-Structs memset and ZeroMemory is ok and it’s pretty useful too, but in C++ go for constructors whenever possible!

MFC does use AFX_ZERO_INIT_OBJECT but carefully! Look up what it does!

One thought on “Careful with memset and ZeroMemory!

Appreciate your comments...