What is the difference between memcpy()
and strcpy()
? I tried to find it with the help of a program but both are giving the same output.
int main() { char s[5]={'s','a','\0','c','h'}; char p[5]; char t[5]; strcpy(p,s); memcpy(t,s,5); printf("sachin p is [%s], t is [%s]",p,t); return 0; }
Output
sachin p is [sa], t is [sa]
If you know the length of a string, you can use mem functions instead of str functions. For example, memcpy is faster than strcpy because it does not have to search for the end of the string. If you are certain that the source and target do not overlap, use memcpy instead of memmove .
strcpy () is meant for strings only whereas memcpy() is generic function to copy bytes from source to destination location. The strcpy ( ) function is designed to work exclusively with strings.
On almost any platform, memcpy() is going to be faster than strcpy() when copying the same number of bytes. The only time strcpy() or any of its "safe" equivalents would outperform memcpy() would be when the maximum allowable size of a string would be much greater than its actual size.
strcpy( ) function copies whole content of one string into another string. Whereas, strncpy( ) function copies portion of contents of one string into another string. If destination string length is less than source string, entire/specified source string value won't be copied into destination string in both cases.
what could be done to see this effect
Compile and run this code:
void dump5(char *str); int main() { char s[5]={'s','a','\0','c','h'}; char membuff[5]; char strbuff[5]; memset(membuff, 0, 5); // init both buffers to nulls memset(strbuff, 0, 5); strcpy(strbuff,s); memcpy(membuff,s,5); dump5(membuff); // show what happened dump5(strbuff); return 0; } void dump5(char *str) { char *p = str; for (int n = 0; n < 5; ++n) { printf("%2.2x ", *p); ++p; } printf("\t"); p = str; for (int n = 0; n < 5; ++n) { printf("%c", *p ? *p : ' '); ++p; } printf("\n", str); }
It will produce this output:
73 61 00 63 68 sa ch 73 61 00 00 00 sa
You can see that the "ch" was copied by memcpy()
, but not strcpy()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With