c - Cannot free data of a buffer after it was reallocated inside recursive function. What can be the reason? -
c - Cannot free data of a buffer after it was reallocated inside recursive function. What can be the reason? -
so faced issue - when have info exceeds initial size of buffer , reallocation within recursive function error freeing buffer.
*malloc: *** error object 0x100106da0: pointer beingness freed not allocated*
here code:
void recprint(file *file, char *buffer, int realbuffersize, int buffersize, char *freech, nodeptr* temp){ //some code here... int *intarr = temp -> usedindices; int = 0; for(i = 0; < 36; i++){ if(intarr[i] == 1){ if(i > 9){ *freech = - 10 + 'a' ; }else{ *freech = + '0'; } realbuffersize++; if (realbuffersize >= buffersize){ buffer = realloc(buffer, (buffersize + 100) * sizeof(char)); // <<--- realloc here buffersize += 100; } freech++; recprint(file, buffer, realbuffersize, buffersize, freech, &temp -> children[i]); //now need remove characters till next turn freech--; *freech = '\0'; } } } void printtrie(file *file, char *initialpath){ initpath = initialpath; if(root.isparent == 0) return; char *buffer; char *freech; int *intarr = root.usedindices; int buffersize = 10; int realbuffersize = 1000; int = 0; for(i = 0; < 36; i++){ buffer = calloc(1001, sizeof(char)); freech = buffer; if(intarr[i] == 1){ if(i > 9){ *freech = - 10 + 'a' ; }else{ *freech = + '0'; } freech++; realbuffersize++; recprint(file, buffer, realbuffersize, buffersize, freech, &root.children[i]); free(buffer); //<<--- getting error here } } }
the comment @whozcraig points out problem. here's suggested fix.
return realloc
ed buffer recprint
.
use free
on returned value of recprint
.
char* recprint(file *file, char *buffer, int realbuffersize, int buffersize, char *freech, nodeptr* temp){ .... // recurse... buffer = recprint(file, buffer, realbuffersize, buffersize, freech, &temp -> children[i]); // , homecoming *current* buffer pointer caller. homecoming buffer; }
in printtrie
:
buffer = recprint(file, buffer, realbuffersize, buffersize, freech, &root.children[i]); free(buffer);
c realloc
Comments
Post a Comment