关于argv和strncpy()的困惑

遇到一个问题,命令行参数复制到字符串后打印出来的结果与直接打印命令行参数的结果不一致。

不清楚是哪里的问题。

 

#include <stdio.h>
#include <string.h>
#define LEN 5
int main(int argc, char* argv[])
{
    char s1[LEN];
    char s2[LEN];

    for(int i = 0; i<LEN; i++)
    {
        s1[i] = '\0';
        s2[i] = '\0';
    }

    printf("%s\n%s\n", s1, s2);

    // 直接打印命令行参数
    for(int i = 1; i < argc; i++)
        printf("%s\n", argv[i]);

    // 将命令行参数复制到字符串再打印
    strncpy(s1, argv[1], LEN);
    strncpy(s2, argv[2], LEN);
    printf("%s\n%s\n", s1, s2);

    return 0;
}

 

运行:

test.exe tmp temp

结果是对的:



tmp
temp
tmp
temp

但是,运行:

test.exe tmp tempmoreword

结果:



tmp
tempmoreword
tmp
tempmtmp

即,命令行参数超出strncpy()指定的字符串长度时会出错。

 

结论,因为指定的复制字符串长度并不是是n个字符,当n>目标字符串长度时会溢出。

应该改为

strncpy(s1, argv[1], strlen(s1)-1);

转载于:https://www.cnblogs.com/stayathust/p/3913453.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值