C++ memcpy to char* from c_str

memcpy doesn't know what is a string. you give it a range to copy. it depends on strlen here to provide the termination point of range


Yes, this will work as long as your string in from is shorter than 20. Oh, no, wait, we are also copying the NULL terminator so it must be shorter than 19. I guess you see how that can lead to some confusion.

Which is by the way exactly the reason why this code is dangerous: I am assuming this is demo code and your actual code will get that string from some sort of input. At that moment you will not be able to control how long it is. You can truncate it but you might forget to do that which means that your program will be copying content to memory that possibly does not belong to it. This might lead to a crash but at least to undefined behaviour as you are overwriting memory that might contain other important data.

Using the string class actually helps to avoid such problems by not having to specify the string length. I would suggest using this class and only do operations involving c_str() when absolutely necessary.


You should use std::string to copy strings. However, if you want to do it like that you should use strcpy instead of memcpy

int main(int argc, char** argv)
{
  std::string from = "hello";
  char to[20];
  strcpy(to, from.c_str());
  std::cout<< to << std::endl;
  return 0;
}