title: How to implement Reference counting in C?
body: <p>read about it <a href="http://en.wikipedia.org/wiki/Reference_counting" rel="noreferrer">here</a>. </p>
  
  <p>I need to implement a variation of such an interface, say we are given a large memory space to manage there should be getmem(size) and free(pointer to block) functions that has to make sure free(pointer to block) can actually free the memory if and only if all processes using that block are done using it.</p>
  
  <p>What I was thinking about doing is to define a <code>Collectable</code> struct as pointer to block, size of it, and process using it count. then whenever a process using a <code>Collectable</code> struct instance for the first time it has to explicitly increment the count, and whenever the process <code>free()</code>'s it, the count is decremented.</p>
  
  <p>The problem with this approach is that all processes must respond to that interface and make it explicitly work : whenever assigning collectable pointer to an instance the process must explicitly inc that counter, which does not satisfy me, I was thinking maybe there is a way to create a macro for this to happen implicitly in every assignment?</p>
  
  <p>I'm seeking of ways to approach this problem for a while, so other approaches and ideas would be great...</p>
  
  <p><strong>EDIT :</strong> the above approach doesn't satisfy me not only because it doesn't look nice but  mostly because I cant assume a running process's code would care for updating my count. I need a way to make sure its done without changing the process's code...</p>