This article transferred from: http://my.oschina.net/renhc/blog/36345
If you ask for the memcpy in the interview, be careful, there are traps.
First look at the explanation of the standard memcpy ():
?
12 |
void * memcpy ( void *dst, const void *src, size_t n); //If copying takes place between objects that overlap, the behavior is undefined. |
Note the following note, the behavior of the function is undefined for the case where the address overlaps.
As a matter of fact, the trap is also in this, when you implement memcpy (), you need to consider the case of overlapping addresses.
In addition, the standard library provides the memory copy function when the address overlaps: memmove (), so why consider rewriting the memcpy () function?
Because of the implementation efficiency of the memmove () function, the function copies the source string into the temporary buf, and then writes the destination address from the temporary buf, adding an unnecessary overhead.
The implementation of memcpy () is given below, in order to differentiate it from standard library functions, we implement its wrapping function:
?
123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h> void *Memcpy(
void *dst,
const void *src,
size_t size);
int main(
int argc,
char *argv[])
{
char buf[100] =
"abcdefghijk"
;
//memcpy(buf+2, buf, 5);
Memcpy(buf+2, buf, 5);
printf
(
"%s\n"
, buf+2);
}
void *Memcpy(
void *dst,
const void *src,
size_t size)
{
char *psrc;
char *pdst;
if
(NULL == dst || NULL == src)
{
return NULL;
}
if
((src < dst) && (
char *)src + size > (
char *)dst)
// 自后向前拷贝
{
psrc = (
char *)src + size - 1;
pdst = (
char *)dst + size - 1;
while
(size--)
{
*pdst-- = *psrc--;
}
}
else
{
psrc = (
char *)src;
pdst = (
char *)dst;
while
(size--)
{
*pdst++ = *psrc++;
}
}
return dst;
}
|
"Turn" "C-memcpy" to implement the function