Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to/can I free a void pointer in C?

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?

like image 374
Serket Avatar asked Jan 01 '23 02:01

Serket


1 Answers

You have to answer two questions first:

  • Was it previously allocated with a malloc family function (e.g. calloc)?
  • Did you inherit ownership of it when making the function call?

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.

like image 69
tadman Avatar answered Jan 10 '23 18:01

tadman