I have a void pointer as a parameter for a function. It is currently pointing to an int. When I try to free it, it returns a bus error. Should I be freeing void pointers? If so, how do I do so?
You have to answer two questions first:
malloc
family function (e.g. calloc
)?If the answer to both of those is "Yes", then it's at your discretion, though presumably you'd do it at the appropriate time and place to avoid "use after free" type bugs.
When you inherit ownership of a pointer you inherit the responsibility for calling free()
when you're done using it, or passing on ownership to another part of your code. If you fail in this responsibility you have memory leaks.
As a general rule you should never free()
a pointer unless you know with certainty that's what you're supposed to do, and you're allowed to do it.
Some functions return pointers to things that you do not own, and even if you did, they're not valid for free()
because they may be offset somehow. Only the original pointer returned from the malloc
-type function can be used with free()
.
For example:
void* getBuffer(size_t size) {
globalBufferOffset += size;
return &globalBuffer[globalBufferOffset];
}
This returns a pointer in the middle of some structure that may or may not be dynamically allocated. You don't own it. You should not call free()
on it.
Read the documentation very carefully to understand your responsibilities. You may need to call a special free-type function when you're done with the pointer. You may not. You may need to pay attention to thread safety. There's a lot of things that can be going on here you need to be aware of before making a decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With