【发布时间】:2018-02-01 16:00:04
【问题描述】:
我正在尝试在 char 数组中添加 10 个包含单词“data”的字符串并返回结果。这是我的代码:
#include <stdio.h>
#include <string.h>
char* concat () {
char src[50], dest[1];
strcpy(src, "data");
int i =0;
for (i=0; i<=10; i++) {
strcat(dest, src);
strcat(dest, ",");
}
return(dest);
}
int main () {
printf("Final destination string : |%s|", concat());
return 0;
}
但是当我返回我的 dest char 数组时,我遇到了分段错误。
【问题讨论】:
-
请注意,重复使用
strcat()会导致二次行为(一旦您对底层内存管理进行了整理)。我正在与一些同事一起重现客户问题,他们创建了代码以使用strcat()在一个大字符串中生成 700,000 个数字。该程序运行了大约 70 秒,生成了近 6 MiB 的字符串。我重写了它以使用memmove()而不是strcat(),它只用了不到 0.1 秒——相差约 700 倍。诚然,这是一个极端的例子,但它说明了问题。 (也可以查看画家什莱米尔。)