Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memset on structures in C++

Tags:

c++

memset

memcmp

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) );
like image 437
garry Avatar asked May 05 '10 14:05

garry


People also ask

What is memset used for in c?

The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.

Is memset faster than a loop?

Most certainly, memset will be much faster than that loop. Note how you treat one character at a time, but those functions are so optimized that set several bytes at a time, even using, when available, MMX and SSE instructions.

Does memset need to be freed?

No overhead of memory freed is there for the programmer in the memset function as it does not allocate any memory which needs to be freed explicitly.

Is 0 same as memset?

Note: We can use memset() to set all values as 0 or -1 for integral data types also.


2 Answers

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

like image 166
Ben Hymers Avatar answered Nov 02 '22 23:11

Ben Hymers


Can you? Yes, probably. Should you? No.

While it will probably work, you're losing the state that the constructor has built for you. Adding to this, what happens when you decide to implement a subclass of this struct? Then you lose the advantage of reuseable code that C++ OOP offers.

What you ought to do instead is create a constructor that initializes the members for you. This way, when you sublass this struct later on down the line, you just use this constructor to aid you in constructing the subclasses. This is free, safe code! use it!

Edit: The caveat to this is that if you have a huge code base already, don't change it until you start subclassing the structs. It works as it is now.

like image 39
San Jacinto Avatar answered Nov 03 '22 00:11

San Jacinto