Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between memset and _strnset

Tags:

c++

c

memset

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?

like image 352
pistachiobk Avatar asked Sep 18 '15 21:09

pistachiobk


1 Answers

_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.

like image 116
Adam Avatar answered Sep 29 '22 07:09

Adam