使用strcat和realloc进行连接会产生意外错误

Aka*_*aks 3 c linux string gcc string-concatenation

我遇到过所谓的神秘realloc invalid next size error,我gcclinux我的代码上使用的是

 #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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

(我的可能是重复的问题)这里解决方案的某个地方是避免strcat和使用memcpy,但在我的情况下,我真的想连接字符串.上面的代码适用于这样的920次迭代,但是在1920的情况下realloc给出了无效的新大小错误.请帮助找到连接的替代方案,期待对像我这样的懒惰程序员来说是一个有用的问题.

das*_*ght 5

您的代码有几个问题:

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

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

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

int main() {
   int i;
   char *buf= malloc(1);
   *buf='\0';
   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);
   }
}
Run Code Online (Sandbox Code Playgroud)

演示.