Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy vs. memcpy

Tags:

c

memcpy

strcpy

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] 
like image 578
Sachin Chourasiya Avatar asked May 24 '10 16:05

Sachin Chourasiya


People also ask

Which is faster memcpy or strcpy?

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 .

What is difference between memcpy and strcpy?

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.

Is memcpy safer than strcpy?

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.

Which is better strcpy or strncpy?

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.


1 Answers

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().

like image 161
egrunin Avatar answered Sep 22 '22 13:09

egrunin