3、strcpy, strncpy和memcpy

1、strcpy函数

char *strcpy(char *s2, const char *s1);
strcpy 是依据 “\0” 作为结束判断的,如果 s2 的空间不够,则会引起 内存泄漏,工程中禁止使用该函数。

char * strcpy(char *dst,const char *src) 
{
    assert(dst != NULL && src != NULL); 

    char *ret = dst;

    while ((*dst++=*src++)!='\0');

    return ret;
}

2、strncpy函数

char *strncpy(char *s2, const char *s1, size_t n);
为了修复strcpy存在内存泄漏的风险,引入了strncpy函数。
strcpy和strncpy都只能用于字符串的copy。

char *mystrncpy(char *dst, const char *src, size_t n)
{
    assert(dst != NULL && src != NULL);

    char *dstCopy = dst;
    while (n && (*dst++ = *src++))
        n--;

    if (n) {
        while (--n)
            *dst++ = '\0';
    }

    return dstCopy;
}

1、memcpy函数

void *memcpy(void *s1, const void *s2, size_t n);
memcpy可以实现任意内容的copy

void *mymemcpy(void *dst,const void *src,size_t num)
{
    assert((dst!=NULL)&&(src!=NULL));
    int wordnum = num/4;//计算有多少个32位,按4字节拷贝
    int slice = num%4;//剩余的按字节拷贝
    int * pintsrc = (int *)src;
    int * pintdst = (int *)dst;
    while(wordnum--)
          *pintdst++ = *pintsrc++;
    while (slice--)
          *((char *)pintdst++) =*((char *)pintsrc++);
    return dst;
}

strcpy和memcpy的区别
1、复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容