Search code examples
c++memorymemory-managementmemset

Why or why not use memset in C++?


I have a lot of memset in a program which I have to maintain. Is it a good practice in modern C++ to use memset?

Why and why not?

If not, what should be preferred to memset?


Solution

  • 90% of the time you should use std::fill instead of memset. This is because std::fill will work correctly with classes, and it will also work when setting arrays of non-byte types to a non-zero value. For example, you can memset an array of ints to 0 but you can't memset an array of ints to 0x12345678. With std::fill you can.

    Good compilers can optimize std::fill to a memset where suitable. In the cases they don't, any performance impact is likely to be negligible.

    Using std::fill when a memset would be faster isn't dangerous. Using memset where std::fill should have been used is dangerous. Default to std::fill.

    Ditto for memcpy and std::copy