Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation using strcat and realloc produce unexpected errors

I have encountered so called cryptic realloc invalid next size error , I am using gcc on linux my code is

 #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);
    }
  }

(mine might be duplicate question) here the solution somewhere lies by avoiding strcat and to use memcpy , But in my case I really want to concatenate the string . Above code works for good for such 920 iterations but in case 1920 realloc gives invalid new size error. Please help to find alternative of concatenating , looking forward to be a helpful question for lazy programmers like me .

like image 804
Akaks Avatar asked Nov 20 '25 06:11

Akaks


2 Answers

Your code has several issues:

  • You are not accounting for null terminator when deciding on the new length - it should be size = strlen(buf)+strlen(loc)+1;
  • You are ignoring the result of realloc - you need to check it for zero, and then assign it back to buf
  • You do not initialize buf to an empty string - this would make the first call of strlen produce undefined behavior (i.e. you need to add *buf = '\0';)

Once you fix these mistakes, your code should run correctly:

#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);
   }
}

Demo.

like image 186
Sergey Kalinichenko Avatar answered Nov 22 '25 21:11

Sergey Kalinichenko


buf is not a valid string so strcat() will fail since it expects a \0 terminated string.

If you want to realloc() buf then you should assign the return value of realloc() to buf which you are not doing.

char *temp = realloc(buf,size+1);
if(temp != NULL)
buf = temp;
like image 24
Gopi Avatar answered Nov 22 '25 21:11

Gopi