strcpy问题

本文探讨了strcpy和strncpy函数在字符串复制时的用法和潜在风险,特别关注源和目的地址重叠可能导致的不确定性行为。通过示例代码演示了如何避免此类问题并提供了备选实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     The strcpy() function copies string s2 to s1, including  the
     terminating  null character, stopping after the null charac-
     ter has been copied. The strncpy() function copies exactly n
     bytes,  truncating  s2  or  adding  null characters to s1 if
     necessary. The result will not  be  null-terminated  if  the
     length  of  s2  is  n or more. Each function returns s1.  If
     copying  takes  place  between  objects  that  overlap,  the

     behavior of strcpy(), strncpy(), and strlcpy() is undefined.


在x86&Solaris系统上,strcpy函数出现复制出错,查看帮助后发现字符串类函数族要求不能出现源和目的重叠的情况,否则结果是不确定的,如下

int main(int argc, char *argv[])
{
        char    sid[64]={0};
        int     len;
        char    *sid = argv[1];


        strcpy(sid, "141208301208558618237085283");
        printf("sid,%s,%d\n", sid, strlen(sid));


        if(strncmp(&sid[12], "86", 2)){
                //strcpy( sid, &sid[2] ); 可能会出现错误
                memmove(sid, &sid[2], strlen(sid)+1-2);
                printf("sid2:[%s],%u\n", sid, strlen(sid));
        }
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值