Reputation: 121
when I compile this piece of code, the pointer freed not allocated error pops up. Could someone please explain why that is? Thank you!
static int make_buffer(FILE *input, char *buffer[]){
*buffer = (char *)malloc(INIT_BUFFER_SIZE*sizeof(char));
int buffer_size = INIT_BUFFER_SIZE;
int txt_size = 0;
char cha;
while((cha = fgetc(input)) != EOF){
if (txt_size == buffer_size){
*buffer = (char *)realloc(buffer, buffer_size*2*sizeof(char));
buffer_size *= 2;
}
(*buffer)[txt_size] = cha;
txt_size ++;
}
free(*buffer);
return txt_size;
}
Upvotes: 0
Views: 371
Reputation: 7698
It means that the code is attempting to free something that was not allocated using malloc/realloc. In your case, I think the problem is in
*buffer = (char *)realloc(buffer, buffer_size*2*sizeof(char));
which should be
*buffer = realloc(*buffer, buffer_size*2);
Probably also want to check the result of realloc just for form. Note I simplified yours a bit in that sizeof(char) == 1 by definition and the cast shouldn't be needed these days (it used to be). The commend by David S. about the usefulness of freeing the result is also valid.
Upvotes: 2