Search code examples
c++memsetmemcmp

Using memset on structures in C++


I am working on fixing older code for my job. It is currently written in C++. They converted static allocation to dynamic but didn't edit the memsets/memcmp/memcpy. This is my first programming internship so bare with my newbe-like question.

The following code is in C, but I want to have it in C++ ( I read that malloc isn't good practice in C++). I have two scenarios: First, we have f created. Then you use &f in order to fill with zero. The second is a pointer *pf. I'm not sure how to set pf to all 0's like the previous example in C++.

Could you just do pf = new foo instead of malloc and then call memset(pf, 0, sizeof(foo))?

struct foo { ... } f;
memset( &f, 0, sizeof(f) );

//or

struct foo { ... } *pf;
pf = (struct foo*) malloc( sizeof(*pf) );
memset( pf, 0, sizeof(*pf) );

Solution

  • Yes, but only if foo is a POD. If it's got virtual functions or anything else remotely C++ish, don't use memset on it since it'll stomp all over the internals of the struct/class.

    What you probably want to do instead of memset is give foo a constructor to explicitly initialise its members.

    If you want to use new, don't forget the corresponding delete. Even better would be to use shared_ptr :)