使用 strcat 和 realloc 的串联产生意外错误

Concatenation using strcat and realloc produce unexpected errors

我遇到了所谓的神秘 realloc invalid next size error ,我在 linux 上使用 gcc 我的代码是

 #include<stdio.h>
 #include<stdlib.h>
 #include<string.h>

int main()
{
 int i;
 char *buf;
 char loc[120];
 buf = malloc(1);
 int size;

 for(i=0;i<1920;i++)
  {
    sprintf(loc,"{Fill_next_token = my_next_token%d; Fill_next_token_id = my_next_token_id = my_next_token_id%d}",i,i);
    size = strlen(buf)+strlen(loc);
    printf("----%d\n",size);

    if(!realloc(buf,size))
    exit(1);
    strcat(buf,loc);
    }
  }

(我的问题可能是重复的)here 某处的解决方案在于避免 strcat 并使用 memcpy ,但就我而言,我真的想连接字符串。上面的代码适用于这样的 920 次迭代,但万一 1920 realloc 给出无效的新大小错误。请帮助寻找连接的替代方法,期待成为像我这样的懒惰程序员的一个有用的问题。

buf 不是有效的字符串,因此 strcat() 将失败,因为它需要一个 [=13=] 终止的字符串。

如果你想 realloc() buf 那么你应该将 realloc() 的 return 值分配给你没有做的 buf。

char *temp = realloc(buf,size+1);
if(temp != NULL)
buf = temp;

要点1.始终使用realloc()的return值来访问新分配的内存。

第 2 点。strcat() 需要一个空终止字符串。检查第一个迭代案例。

您的代码有几个问题:

  • 您在决定新长度时没有考虑空终止符 - 它应该是size = strlen(buf)+strlen(loc)+1;
  • 您忽略了 realloc 的结果 - 您需要检查它是否为零,然后将其分配回 buf
  • 您没有将 buf 初始化为空字符串 - 这将使 strlen 的第一次调用产生未定义的行为(即您需要添加*buf = '[=16=]';)

修正这些错误后,您的代码应该 运行 正确:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
   int i;
   char *buf= malloc(1);
   *buf='[=10=]';
   char loc[120];

   for(i=0;i<1920;i++) {
      sprintf(loc,"{Fill_next_token = my_next_token%d; Fill_next_token_id = my_next_token_id = my_next_token_id%d}",i,i);
      int size = strlen(buf)+strlen(loc)+1;
      printf("----%d\n",size);
      char *tmp = realloc(buf,size);
      if(!tmp) exit(1);
      buf = tmp;
      strcat(buf, loc);
   }
}

Demo.