strcpy() uses '\0' as the stopping character while memcpy() requires you to specify how many bytes are being copied. memcpy() isn't guaranteed to be safe if the source and destination blocks overlap while memmove() does have that guarantee at the cost of performance.

Due to the types involved, the mem* functions are also more generic than the str* functions.

Quoted Text Here

strcpy() uses '\0' as the stopping character

char str[] = "mem\0abc";
char str1[20];
memcpy (str1,str,10);
//strcpy(str1,str);
puts (str1);

both memcpy and strcpy giving me same output i.e. mem

strcpy() and memcpy() aren't the ones doing the outputing. Obviously if there's a null character in the middle of the string, puts() will stop on it.

this means when i used memcpy the whole string is copied in str1 while using strcpy str1 contains only "mem"??

this means when i used memcpy the whole string is copied in str1 while using strcpy str1 contains only "mem"??

Yes, though since you told memcpy() to copy 10 bytes, you wrote too many characters and invoked undefined behavior. str only contains 8 characters, after all (including null characters).

and what about memcpy and memmov?
can u explain me with the help of a code?

Edited 4 Years Ago by shanki himanshu

str1="strings are good");
memmove(str1+8,str1+11,4);
returns------ strings are are good
memcpy(str+8,str1+11,4)
returns------ strings are read

str1="strings are good");
memmove(str1+8,str1+11,4);
returns------ strings are are good
memcpy(str+8,str1+11,4)
returns------ strings are read

i run the above code.
i am getting "strings googood" as my output for both cases
i understand my memmove output but why it is same as memcpy?

Edited 4 Years Ago by shanki himanshu

i understand my memmove output but why it is same as memcpy?

Both functions produce the same results. The only real difference is whether the destination and source buffers overlap. If they don't, then use memcpy(), otherwise if they do then use memmove().

This article has been dead for over six months. Start a new discussion instead.