Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should C++ programmer avoid memset?

I heard a saying that c++ programmers should avoid memset,

class ArrInit {
    //! int a[1024] = { 0 };
    int a[1024];
public:
    ArrInit() {  memset(a, 0, 1024 * sizeof(int)); }
};

so considering the code above,if you do not use memset,how could you make a[1..1024] filled with zero?Whats wrong with memset in C++?

thanks.

like image 600
Jichao Avatar asked Oct 10 '22 00:10

Jichao


People also ask

Can memset be used in c?

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

What can I use instead of memset?

For one thing, sizeof(my_array) returns the total number of bytes in the data structure and not the number of elements. Also, your code would've just copied the pointer. You need to actually copy the data it points to since the target is not pointers--it's actual structures.

When should we use memset?

Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.

Is memset faster than a loop?

You can assume that memset will be at least as fast as a naive implementation such as the loop. Try it under a debug build and you will notice that the loop is not replaced. That said, it depends on what the compiler does for you. Looking at the disassembly is always a good way to know exactly what is going on.


1 Answers

In C++ std::fill or std::fill_n may be a better choice, because it is generic and therefore can operate on objects as well as PODs. However, memset operates on a raw sequence of bytes, and should therefore never be used to initialize non-PODs. Regardless, optimized implementations of std::fill may internally use specialization to call memset if the type is a POD.

like image 52
Charles Salvia Avatar answered Oct 23 '22 03:10

Charles Salvia