为什么要使用的函数strncpy代替strcpy的? [英] Why should you use strncpy instead of strcpy?

查看:1359
本文介绍了为什么要使用的函数strncpy代替strcpy的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我添加了示例的源

我碰到<少时href=\"http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/rzan5mst269.htm\">this例如:

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'\n", destination);
return_string = strcpy(destination, source);
printf("after strcpy, dest becomes '%s'\n\n", destination);

/* This is how strncpy works */
printf( "destination1 is originally = '%s'\n", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'\n", destination1 );

这产生这样的输出:

Which produced this output:

destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'

destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'

这让我不知道为什么会有人想要这种效果。它看起来像这将是混乱的。这个程序让我觉得你可以基本结束了某人的名字。(比如汤姆·布罗考)与汤姆Bro763复制。

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 取决于一个尾随 \\ 0 ,它可能不会总是发生。

strncpy combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing \0, 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天全站免登陆