memset,memcpy,strcpy

strcpy

char *strcpy( char *dest, const char *src );

dest-pointer to the byte string to copy to
src-pointer to the null-terminated byte string to copy from

Copies the byte string pointed to by src to byte string pointed to by dest.If the strings overlap, the behavior is undefined.

ps.src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串,返回指向dest的指针。strcpy 就只能拷贝字符串,它遇到’\0’就结束拷贝,不会拷贝’\0’。例如:

char a[100],b[50];
strcpy(a,b);
//*a='\0';

实现代码

char * strcpy(char *dst, const char *src)
{
    if(src == NULL || dst == NULL)
          return NULL;  //throw "Invalid argument(s)";异常机制
    //assert((strDest!=NULL) && (strSrc !=NULL)); 
    if(dst == src)
          return dst;
    char *ret = dst;//保存原始的dst初始地址
    while((*dst++ = *src++) != '\0') ;//保证最后dst以'\0'结尾
    return ret;
}

memcpy

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

dest-pointer to the memory location to copy to
src-pointer to the memory location  to copy from
count-number of bytes to coy

Copies count characters from the object pointed to by src to the object pointed to by dest. If the objects overlap, the behavior is undefined.

ps.src和dest所指内存区域不能重叠(陷阱),函数返回指向dest的指针。一般用于内存拷贝,可以拷贝任何数据类型的对象,也可指定数据长度。例如:

char a[100],b[50];
memcpy(b,a,sizeof(b)); //sizeof(a)会导致内存溢出

实现代码

 void  *memcpy(void *dst, const void *src, size_t len)
{
        assert((dst != NULL) && (src != NULL));
        byte *pTo= (byte *) dst ;
        byte *pFrom= (byte *) src;
        while(len-- > 0 )
            *pTo++ = *pFrom++ ;
        return dst;
}

对于地址重叠的情况,该函数的行为是未定义的,改进如下:

void * memcpy(void *dst, const void *src, size_t len)
{
    assert(src != NULL && dst != NULL);
    void *ret = dst;
    int i = len;
    //防地址重叠
    if(src > dst)
    {
        char *csrc = (char *)src;
        char *cdst = (char *)dst;
        while(i--)
            *cdst++ = *csrc++;
     }
     else
     {
        char *csrc = (char *)src + len - 1;
        char *cdst = (char *)dst + len - 1;
        while(i--)
            *cdst-- = *csrc--;
     }
    return ret;
}

memset

void* memset( void* dest, int ch, size_t count );

dest-pointer to the object to fill
ch-fill byte
count-number of bytes to fill

Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest.

ps.memset用于将dest所指内存区域的前count个字节设置成字符ch,返回指向dest的指针。一般用于对定义的字符串初始化为’ ‘或者’\0’。例如:

 char a[100];
 memset(a,'\0',sizeof(a));

实现代码

void * memset( void* dest, int ch, size_t count )
{
	char *pTo = (char*)dest;
	assert(dest != NULL);
	while(count-- > 0)
		*pTo++ = (char)ch;
	return dest;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *