Can I do this in C? Valgrind complains that realloc produces an invalid free?
int main(){
void* mem;
// Do stuff
recurfunc(123, mem);
// Do stuff
if(mem)
free(mem);
return 0;
}
void recurfunc(int x, void* mem){
.....
// Do stuff
mem = realloc(mem, newsize);
// Do stuff
recurfunc(x, mem);
.....
}
Yes, it does indeed complain, because the
void *you’re passing in asmemis a copy of the pointer. Changes to the pointer within the function will not be reflected back tomain.If you want to change
memin the function and have it reflected back, you need to pass a pointer to a pointer.The following code illustrates this:
which outputs:
and you can see that the first value is retained in
maindespite it being changed within the function.