为什么要使用 strncpy 而不是 strcpy? [英] Why should you use strncpy instead of strcpy?
本文介绍了为什么要使用 strncpy 而不是 strcpy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经添加了示例的源代码.
我遇到了 这个例子:
char source[MAX] = "123456789";
char source1[MAX] = "123456789";
char destination[MAX] = "abcdefg";
char destination1[MAX] = "abcdefg";
char *return_string;
int index = 5;
/* This is how strcpy works */
printf("destination is originally = '%s'
", destination);
return_string = strcpy(destination, source);
printf("after strcpy, dest becomes '%s'
", destination);
/* This is how strncpy works */
printf( "destination1 is originally = '%s'
", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'
", destination1 );
产生此输出的原因:
destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'
这让我想知道为什么有人会想要这种效果.看起来会很混乱.这个程序让我觉得你基本上可以用 Tom Bro763 复制某人的名字(例如 Tom Brokaw).
Which makes me wonder why anyone would want this effect. It looks like it would be confusing. This program makes me think you could basically copy over someone's name (eg. Tom Brokaw) with Tom Bro763.
使用 strncpy()
优于 strcpy()
有什么好处?
推荐答案
strncpy
通过要求您在其中输入长度来对抗缓冲区溢出.strcpy
依赖于尾随的