www.cnblogs.com/cpsmile/p/4…

Memmove, memcpy, strCPY, memset

The prototype is:

void *memmove( void* dest, const void* src, size_t count );

Char * strcpy(char* dest, const char* SRC);

Void *memcpy(void *dest, const char* SRC, size_t count);

Void * memset(void* dest, int value, size_t num)

(1) Strcpy provides string copying.

That is, strcpy is only used for string copying, and it copies not only the contents of the string, but also the terminator of the string.

(2) Memcpy only provides general memory replication, that is, memcpy has no restrictions on what needs to be copied, so it is more versatile.

(3) The content of the copy is different.

Strcpy can only copy strings, while memcpy can copy anything, such as strings, integers, structures, classes, etc.

(4) Different methods of replication.

Strcpy does not need to specify a length. It ends at the end of the copied string “\0 “, so it is prone to overflow. Memcpy determines the length of the copy based on the third parameter.

(5) Different uses.

Strcpy is usually used when copying strings, but memcpy is used when copying other types of data.

(6) memCPy is just a subset of memmove, memmove in the copy of two overlapping areas of memory can ensure the correct copy, and memcopy is not good, but memcopy is faster than memmove.

Memcpy implementation:

1 //size_t refers to unsigned int 2 char* memcpy(void* dest,const void* SRC, size_t num) 3 {4 char* p_dest = (char*)dest; 5 const char* p_src = (const char*)src; 6 assert((dest ! = NULL) && (src ! = NULL) && (dest ! = src)); 7 while(num-- > 0) 8 *p_dest++ = *p_src++; 9 return dest; 10}Copy the code

Strcpy implementation:

1 char* strcpy(char* dest, const char* src) 2 { 3 assert((dest! =NULL) && (src! =NULL) && (dest! =src)); 4 char* address = dest; 5 while(*dest++ = *src++ ) 6 NULL; 7 return address; 8}Copy the code

Memmove implementation:

 

1 char* memmove(void* dest, const void* src,size_t num) { 2 assert((dest! =NULL) && (src! =NULL) && (dest! =src)); 3 char* p_dest = (char*)dest; 4 const char* p_src = (const char*)src; If (p_dest > p_src &&p_dest < p_src + num) {8 p_dest + num - 1; 9 p_src += num - 1; 10 while(num--) 11 *p_dest-- = *p_src--; *p_dest++ = *p_src++;} 13 else 14 {// dest<=p_src; 17 } 18 return dest; 19}Copy the code

 

Memset implementation:

1 char* memset(void* dest, int value, size_t num) 
2 {
3   assert(dest != NULL);
4   unsigned char* p_dest = (unsigned char*)dest;
5   while(num-- > 0) 
6     *p_dest++ = (unsigned char)value;
7   return dest;
8 }
Copy the code