Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is reference counter and how does it work?

Tags:

c

I've been writing code, and I'm in a point where I should have another program calling my library. I should make a reference counter for the output of my library. Basic idea as I have understood is that, I need to have reference counter struct inside my struct that I want to pass around. So my questions are following:

  1. What should I keep in mind when making a reference counter?

  2. What are complete don'ts when making a reference counter?

  3. Is there really detailed examples where to start with this?

Thank you for your answers in advance!

like image 208
J. Rautava Avatar asked Oct 29 '25 05:10

J. Rautava


1 Answers

Reference counting allows clients of your library to keep reference objects created by your library on the heap and allows you to keep track of how many references are still active. When the reference count goes to zero you can safely free the memory used by the object. It is a way to implement basic "garbage collection".

In C++, you can do this more easily, by using "smart pointers" that manage the reference count through the constructor and destructor, but it sounds like you are looking to do it in C.

You need to be very clear on the protocol that you expect users of your libraries to follow when accessing your objects so that they properly communicate when a new reference is created or when a reference is no longer needed. Getting this wrong will either prematurely free memory that is still being referenced or cause memory to never be freed (memory leak).

Basically, You include a reference count in your struct, that gets incremented each time that your library returns the struct.

You also need to provide a function that releases the reference:

struct Object {
  int ref;
  ....
}

Object* getObject (...) {
  Object *p = .... // find or malloc the object
  p->ref++;
  return p;
}

void releaseReference (Object* p) {
  p->ref--;
  if (p->ref == 0) free(p);
}

void grabReference (Object* p) {
  p->ref++;
}

Use grabReference() if a client of your library passes a reference to another client (in the above example, the initial caller of your library doesn't need to call grabReference())

If your code is multi-threaded then you need to make sure that you handle this correctly when incrementing or decrementing references

like image 186
Eric Petroelje Avatar answered Oct 30 '25 22:10

Eric Petroelje