Search code examples
c++cmemset

Difference between memset and _strnset


I can't figure out what exactly is the difference between the two following implementations:

char str[20] = "Hello World";
_strnset(str, '*', 5); 

and

char str[20] = "Hello World";
memset(str, '*', 5);

They both produce the following outcome:

Output: ***** World!

Is there a preference between them?


Solution

  • _strnset knows it's working with a string, so will respect the null terminator. memset does not, so it won't.

    As for preference,

    • memset is in both the C and C++ standards, _strnset is in neither.
    • if available, _strnset can save you from buffer overflows if you write buggy code.

    If you know you'll stay on Windows, use _strnset. Else memset.