C Language Simulation for oc reference counting and oc reference counting

Source: Internet
Author: User

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

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.