C Language Simulation for oc reference counting and oc reference counting
# Include <stdio. h>
# Include <stdlib. h>
// Introduce the reference counting mechanism in c
// The problem to be solved: 1. What are the pointers to a dynamic memory?
// Set the number of dynamic memory record pointers.
// How large is the dynamic memory size to be opened up?
// If the pointer to c needs to open up n Bytes,
// In fact, n + 4 bytes should be opened
// Assume in c: void * p = xalloc (8)
// Then: in actual xalloc, you should call:
// Int * realp = malloc (12)
// Assume that the memory is as follows:
// [_]
// ^
// |
// |
// Realp p
//
// Release process: xrelease (p)
// This function corresponds to the alloc method of oc
Void * xalloc (int size)
{
Int * realp = malloc (size + 4 );
/** Realp = 1 ;*/
Realp [0] = 1;
Return realp + 1;
}
// Corresponding oc release Method
Void xrelease (void * p)
{
Int * realp = (int *) P-1;
If (realp [0] = 1)
{
Printf ("memory [% p] is actually released... \ n", p );
Free (realp );
}
Else
Realp [0] --;
}
// Retain method corresponding to oc
Void * xretain (void * p)
{
Int * realp = (int *) P-1;
Realp [0] ++;
Return p;
}
// RetainCount method corresponding to oc
Int xretainCount (void * p)
{
Return * (int *) P-1 );
}
Int main (int argc, char ** argv)
{
Int * p = xalloc (4); // The Memory count pointed to by p is: 1
Printf ("p: [% p] indicates the memory count: % d \ n", p, xretainCount (p ));
Int * q = xretain (p); // The Memory count pointed to by p is: 2
// Q = [p retain];
Printf ("p: [% p] indicates the memory count: % d \ n", p, xretainCount (p ));
Xrelease (p); // The Memory count pointed to by p is: 1
Printf ("q: [% p] indicates the memory count: % d \ n", q, xretainCount (q ));
Xrelease (q); // The Memory pointed to by q will be actually released
Return 0;
// A large-sized simulated reference counting mechanism
}