【问题标题】:C function to return a char array generated with strcat in a for loopC 函数在 for 循环中返回用 strcat 生成的 char 数组
【发布时间】: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 倍。诚然,这是一个极端的例子,但它说明了问题。 (也可以查看画家什莱米尔。)

标签: c strcat


【解决方案1】:

我无法返回我的 dest 字符数组,我有分段错误 => 因为 dest 是只有一个字符的数组,你不能将 "data" 存储 10 次到 @987654323 @。而不是 dest[1] ,取 destchar pointer 并动态分配内存。

你可能想像下面那样做

#include <stdio.h>
#include <string.h>
char* concat () {
        char src[50], *dest;
        dest = malloc(100 * sizeof(char)); /* allocating 100 bytes for dest, allocate according to your requirement */
        strcpy(src,  "data");

        int i =0,j;
        for (i=0,j=0; i<=10; i++) {
                strcat(dest+j, src);//first time dest points to starting address
                strcat(dest, ",");
                j = strlen(dest);/* next time put data at dest+j location */
        }
        dest[j]= '\0';
        return dest ;
}
int main () {
        char * ret = NULL;
        printf("Final destination string : |%s|\n", ret = concat());
        free(ret); /* to avoid memory leakage */
        return 0;
}

希望对你有帮助。

【讨论】:

  • sizeof(char) 根据定义始终为 1,因此使用它是多余的。
【解决方案2】:

你有错误的想法,strcat 在连接字符串时分配内存。 错了。因此,通过在strcat 中使用长度为 1 的 char 数组,您调用了未定义的行为,因为它将写入超出单个元素 char 数组边界的内存。

dest 变量也具有自动存储持续时间 - 一旦声明它的范围结束(在这种情况下是函数结束时),您就不能使用它。在其生命周期结束后使用变量是未定义的行为。

另一件事是strcat 的第一个参数是空终止的字符数组,这不是这里的情况,因此使用错误的参数到strcat 也是未定义的行为。

如果dest 可以保存您正在处理此功能的任何连接字符串,您可以这样做

char s[]="data";
char* dest = malloc(MAXLEN);
if(!dest){ perror("malloc"); exit(EXIT_FAILURE);}
for(int i = 0; i <10; i++){
   if(!i) strcpy(dest,src);
   else
     strcat(dest,src);
   strcat(dest,",");
}
return dest;

main():

char *s;
printf("Final destination string : |%s|", (s=concat()));
free(s);

【讨论】:

  • @achal.:仔细检查。
  • @achal.: 因为它保存了函数concat中malloc返回的分配块的内存。
  • 哦..我没看到。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 2021-01-06
相关资源
最近更新 更多