Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent for memset on char*

Tags:

c++

memcpy

memset

I have this code

  char * oldname = new char[strlen(name) + 1];

  memcpy(oldname,name,strlen(name) + 1);

  name = new char[strlen(oldname) + strlen(r.name) + 1];
  memset(name, '\0', strlen(name));

  strcat(name,oldname);
  strcat(name," ");
  strcat(name,r.name);

I understand that it is a no no to use memcpy and memset but I haven't understood exactly how to use this in C++, preferably without std.

Does anyone know? Thank you.

like image 997
Para Avatar asked Jan 24 '10 22:01

Para


2 Answers

In general, there's std::fill. http://www.cplusplus.com/reference/algorithm/fill/

Or in this particular instance, you should consider using std::vector<char>.

(Note that memset can still be used in C++ if you use #include <cstring>, although it's less idiomatic in C++.)

like image 125
jamesdlin Avatar answered Oct 18 '22 19:10

jamesdlin


One possible replacement for memset when you have an array of object types is to use the std::fill algorithm. It works with iterator ranges and also with pointers into arrays.

memcpy calls can usually be replaced with calls to std::copy.

e.g.

std::copy(name, name + strlen(name) + 1, oldname);
// ...
std::fill(name, name + strlen(name), '\0');

memset and memcpy are still there and can be used when appropriate, though. It's probably a bigger no-no from many C++ developer's point of view to be using a raw new and not using a resource managing object. It's much better to use a std::string or a std::vector<char> so that memory deallocation is automatic and the code is more exception safe.

like image 24
CB Bailey Avatar answered Oct 18 '22 17:10

CB Bailey