Home > Windows API > Careful with memset and ZeroMemory!

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.

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

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

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 ));

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!

Advertisements
  1. December 22, 2008 at 12:31 pm

    thank you.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: