tags:

views:

731

answers:

4

I've read the function headers, but I'm still not sure what exactly the difference is in terms of use cases.

Thanks!

+5  A: 

memset() sets all of the bytes in the specified buffer to the same value, memcpy() copies a sequence of bytes from another place to the buffer.

char a[4];
memset(a, 7, sizeof(char)*4);
/*
* a is now...
*
* +-+-+-+-+
* |7|7|7|7|
* +-+-+-+-+
*/

char b[] = {1,2,3,4};
char c[4];
memcpy(c, b, sizeof(char)*4);
/*
* c is now...
*
* +-+-+-+-+
* |1|2|3|4|
* +-+-+-+-+
*/
Amber
+8  A: 

memcpy copies from one place to another. memset just sets all pieces of memory to the same.

example:

memset(str, '*', 50);   // sets the first 50 characters of the string str to *.
memcpy(str2, str1, 50); // copies the first 50 characters of str1 to str2.
Peter
It's worth pointing out that the mem*() functions *don't* know about string terminators. The second example above will do bad things if str1 is shorter than 50 characters. It's only safe to use mem*() functions on string data when you've already validated the lengths involved.
unwind
absolutely. take this as only an example.
Peter
it might be worth pointing out that if you do want to copy two strings use:strncpy(str2, str1, 50);This will safely copy str1 to str2 stopping the copy at the first '\0' string terminator it detects in str1, but has the safety net that it will not copy more than 50 characters should str1 be corrupt or longer than 50 bytes.
EndsOfInvention
Of course strncpy goes wrong in some cases where strcpy would work: for instance if you've arranged for str2 to be as long as necessary (i.e. length of str1, with space for nul terminator), but str2 is actually shorter than than your 50-char limit. strncpy is not a safe version of strcpy, it just has different pitfalls. In any case use (or re-implement) strcpy_s instead: it always nul-terminates the result whereas strncpy does not always nul-terminate. strcpy_s also fails instead of truncating overlong strings: truncation usually leads to another bug further down the line.
Steve Jessop
Well, this is correct but more specifically the mem*() functions don't know or care about strings at all. They deal with memory.
BobbyShaftoe
+3  A: 

memset sets a block of memory to a single value. memcpy copies the content of a block into another block.

Perhaps you'd be interested in the difference between memcpy and memmove. Both do the same, but the latter works even if the source and destination overlap.

Tordek
+2  A: 

memset() is used to set all the bytes in a block of memory to a particular char value. Memset also only plays well with char as it's its initialization value.

memcpy() copies bytes between memory. This type of data being copied is irrelevant, it just makes byte-for-byte copies.

Kyle Rozendo