memset, clean your container before you put your stuff in

It is very important to clean your container before you put your stuff in. It might dirty your stuff if you do not do so. This happen to memory storage.

By declaring a variable such as objects of class is just preserved you a bulk of memory space. It doesn’t come with the memory clean up. We tends to forget to reset all to zero first before we use. Because, usually it is okay, it didn’t cause any problem.

MY_CLASS myClass
for (i=0;i<Len;i++)
     myClass.FeedData(i,szData[i]);

You are just lucky, if it doesn’t cause any problem yet. Doing that is injecting a hidden bug to your code. I have this bad habits too and I suffered from it. And Now, I gonna put a full stop on this. It wasted me an hour to find the bug yesterday.

Clean it up, before it poison your data. A tiny dust can make you sick and it sometimes leads you to death. So reset it to all zero.

void *memset(void *s, int c, size_t n);

Just a line of code that will safe you from many hours of debugging.

MY_CLASS myClass

memset(&myClass,0,sizeof(myClass));

for (i=0;i&lt;Len;i++)
     myClass.FeedData(i,szData[i]);

3 thoughts on “memset, clean your container before you put your stuff in

  1. Yes so true. However I also have this habbit, and I never cleared the class this way, only arrays. But it is true. Some nasty pointers or garbage data can make debugging really hard.

  2. This is a bad idea. As the user of MY_CLASS, you have no idea what it consists of. Clearing using memset should only be done in the constructor of MY_CLASS (and only then if needed).

    If you follow the article on std::string things will go horribly wrong on most implementations (it stores a pointer to the actual data, which memset will wipe).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>