I have one of these situations that makes me think I don't really understand something I thought I understood, which it's been true before...I have a global buffer that I want to free() and reuse like this:
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *buffer;
void testfunc (int toggle) {
char X[]="XXXXXXXXX";
if (toggle==0) { buffer=malloc(11);
strcpy(buffer,X);}
else {buffer=realloc(buffer,strlen(buffer)+11);
strcat(buffer,X);
}
}
int main() {
testfunc(0);
testfunc(1);
puts(buffer);
free(buffer); // end of 1st iteration
testfunc(0);
testfunc(1);
puts(buffer);
free(buffer);
return 0;
}
This code works, but does anyone know what could cause it to produce a double-free/corruption abort at "end of 1st iteration" if:
- THERE IS ONLY ONE free() call previously in the script,
- "buffer" was just malloc'd and realloc'd as above, previous to the free(),
- the total number of bytes allocated to buffer is >0
To me this just does not make sense, it's something I've done many times before (freeing and reusing a malloc'd buffer in a loop) and again, it does not make sense to me, but it keeps happening anyway: I have a global char*, I allocate it memory in a function, it serves it's purpose, then I free it for reuse in main() -- and I get a double free/corruption abort. What factors am I ignorant of?