Reputation: 2687
I am parsing a lot of data and I am using C to it. It works for almost all the data but at one point I get the error:
*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x091fb288 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x75ee2)[0xb75d1ee2]
./a.out[0x8049321]
./a.out[0x80494b3]
./a.out[0x804b843]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0xb75754d3]
My code is the following. The conditional is in a loop that iterates successfully for many iterations, but at one point throws the error. My error occurs when free(tmp); is called, however, tmp is only used in this small area of the code.
...
if(tokens_o[i].start != tokens_o[i].end)
{
tmp = printToken(content, &tokens_o[i]);
printf("%s \n", tmp);
free(tmp);
}
...
char *
printToken(char *text, jsmntok_t *token)
{
int size = token->end - token->start;
char *text_token = calloc(size+1, sizeof(char));
if(text_token == NULL)
{
printf("error when reading token \n");
exit(0);
}
strncpy(text_token, text+token->start, size);
return text_token;
}
Upvotes: 2
Views: 114
Reputation: 582
I expect that in one of the iterations the calculated size
is -1. This means that calloc
would be called with with nmemb
set to 0.
According to the man page, calloc
can return a unique pointer value that can later be successfully passed to free
if it is called with nmemb
as 0.
strncpy
is then called with size -1 but the type of n is size_t
(i.e. unsigned) and strncpy
will therefore write outside any allocated boundaries.
Upvotes: 3