memcpy

Hello, does this function memcpy only copy from src to destination. For instance if the src is an array of 5 ints numbered 1-5, and it was all copied, the src pointer and the dest pointer would both point to their own array with numbers 1-5. Or is it more like a move, and they each point to the same array?
It copies the contents from one memory location to another. So in the example you propose, after the call you'd have two arrays with the same values, which can be changed independently of one another.
Note that for memcpy() the source and dest range cannot overlap. If they do, then use std::memove()

http://www.cplusplus.com/reference/cstring/memmove/

Also note that the size of the copy is in bytes - not items. So if moving 5 ints from src to dest then:

 
std::memcpy(dest, src, 5 * sizeof(int));


The return value is dest.
note also that it has the 'pointer issue'.
consider
struct foo
{
string s{"the quick brown fox jumped over a lazy dog"};
int x;
};

foo a,b;
memcpy(&a, &b, sizeof(foo)); //bad: the string cannot be copied this way safely, same as writing foo to a binary file with .write() and getting it back will not work.
memcpy, memset, memmove are pretty fast but they are easy to misuse... take care with them.
Last edited on
Topic archived. No new replies allowed.