为什么要使用 strncpy 而不是 strcpy? [英] Why should you use strncpy instead of strcpy?

查看:43
本文介绍了为什么要使用 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 依赖于尾随的 ,这可能并不总是发生.

strncpy combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing , which may not always occur.

其次,为什么您选择只复制 7 个字符串上的 5 个字符超出了我的理解,但它会产生预期的行为.它只是复制前 n 个字符,其中 n 是第三个参数.

Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n characters, where n is the third argument.

n 函数都用作防御缓冲区溢出的编码.请使用它们代替旧函数,例如 strcpy.

The n functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy.

这篇关于为什么要使用 strncpy 而不是 strcpy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆