【问题标题】:Realloc() inside a function函数内部的 Realloc()
【发布时间】:2022-01-09 13:02:27
【问题描述】:

我正在尝试将我自己的 strcat() 版本与 realloc 混合。所以想法是,传递一个在 main 上声明的 char* 并动态添加内存。

问题是我每次都得到分段错误,我的意思是我尝试了所有我知道的。

这是我的代码,希望有人能帮助我:

主要:

char* nombreCopia = "";
StrcatDynamic(&nombreCopia, argv[1]);
free(nombreCopia);

strcat动态:

    int StrcatDynamic(char** dest, const char* src)
   {
      char* aux;
      printf("%p\n", *dest);
      aux = realloc (*dest, (strlen(src) + strlen(*dest) + 1) );
      

      if (aux == NULL)
      {
         perror("ERROR\n");
      }
      else
      {
         *dest = aux;
      }
      strcat(*dest, src);


      return 0;
   }

【问题讨论】:

  • 代码调用 realloc() 时使用了一个之前从未分配过的指针。 char* nombreCopia = ""; 不会将 nombreCopia 分配给分配的数据。
  • 顺便说一句,strcpy(*dest, src); 没有连接。
  • 那么,您知道修复它的最佳方法是什么吗?加载一些东西?
  • 谢谢我忘了改
  • 如果您将调用站点 init 更改为 char* nombreCopia = NULL;,它应该可以工作。您不能重新分配文字字符串。传递 null 会导致它表现为malloc()

标签: c pointers


【解决方案1】:

你不能freerealloc""产生的字符串。

简单的解决方案:

char* nombreCopia = strdup("");     // In lieu of `char* nombreCopia = "";`

我会做什么:

char* nombreCopia = NULL;           // In lieu of `char* nombreCopia = "";`
( *dest ? strlen(*dest) : 0 )       // In lieu of `strlen(*dest)`

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2020-09-19
    • 2019-05-23
    • 2021-04-12
    相关资源
    最近更新 更多