Concatenation using strcat and realloc throws unexpected errors

I ran into so called cryptic realloc

invalid next size error

, I use gcc

in linux

, my code

 #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 may be a duplicate question) here the solution lies somewhere, avoid strcat

and use memcpy

, but in my case I really want to combine String. The above code works in the interests of such 920 iterations, but in case 1920 realloc

gives an incorrect error of the new size. Please help find an alternative to concatenation, looking forward to a helpful question for lazy programmers like me.

+3


source to share


3 answers


There are several questions in your code:

  • You are not considering the null terminator when choosing a new length - it should besize = strlen(buf)+strlen(loc)+1;

  • You are ignoring the resultrealloc

    - you need to check for zero and then assign backbuf

  • You are not initializing with buf

    an empty string
    - that would make the first call strlen

    result undefined (i.e. you need to add *buf = '\0';

    )

Once you fix these errors, your code should work 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 version

+5


source


buf

is not a valid string, so strcat()

will fail as it expects a \0

terminated string .

If you want realloc()

buf

, you must assign the return value realloc()

to buf, which you don't.



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

      

+1


source


Point 1. Always use the return value realloc()

to access newly allocated memory.

Point 2. strcat()

needs a null-terminated string. Check out the first iteration case.

0


source







All Articles