相关疑难解决方法(0)

为什么要使用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'\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 );
Run Code Online (Sandbox Code Playgroud)

哪个产生了这个输出: …

c buffer-overflow c89 strcpy strncpy

77
推荐指数
5
解决办法
17万
查看次数

标签 统计

buffer-overflow ×1

c ×1

c89 ×1

strcpy ×1

strncpy ×1