关于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);
posted @ 2014-08-14 21:08  liuxia_hust  阅读(275)  评论(0编辑  收藏  举报