strcpy自实现

  为了避免strcpy源串覆盖问题(P220),自实现strcpy。

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>

void myStrcpy(char *to, char *from)
{
    assert(to != NULL && from != NULL);
    while(*from != ''){
        *to ++ = *from ++;
    }
    *to = '';
}

int main()
{
    char s[] = "123456789";
    char d[] = "1234";
    printf("&s= %x, &d= %x
",s,d);
    //在栈空间上,d的起始地址在s的起始地址之前。
    strcpy(d, s);
    //使用strcpy将会对源串s产生覆盖
    printf("s=%s d=%s
",s,d);

    char *str = (char*)malloc(15 * sizeof(char*));
    char *ttr = (char*)malloc(15 * sizeof(char*));
    myStrcpy(str, "123456789");
    myStrcpy(ttr, "1234");
    myStrcpy(ttr, str);
    printf("str=%s ttr=%s
",str,ttr);
    return 0;
}
原文地址:https://www.cnblogs.com/luntai/p/5924871.html