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.
source to share
There are several questions in your code:
- You are not considering the null terminator when choosing a new length - it should be
size = strlen(buf)+strlen(loc)+1;
- You are ignoring the result
realloc
- you need to check for zero and then assign backbuf
- You are not initializing with
buf
an empty string - that would make the first callstrlen
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);
}
}
source to share