Waiting for answer This question has not been answered yet. You can hire a professional tutor to get the answer.

QUESTION

Basic Reference Counting ( Memref ) You are tasked with writing a basic library that will allow a programmer to have their memory garbage collected...

Basic Reference Counting (Memref)

You are tasked with writing a basic library that will allow a programmer to have their memory garbage collected once all references have been lost. It is important to note that this library does not need to deal with cyclic references.

You are to implement 3 functions and a collection of references, with each entry of the collection containing a reference and counter (however you are free to implement this in another way if you feel, as long as it is flexible). Reference may also contain a dependency on another reference (parent) that they are attached to and that if the parent reference is deallocated then the reference counter for the dependent objects must be decremented.

Functions:

new_ref() will allow for allocation of memory based on the size variable and specify if it is dependency of another reference. If the dep argument is NULL then it is a root and does not depend on any other object.

void* new_ref(size_t size, void* dep);

assign_ref() allows the programmer to specify the reference to assign to it and will therefore increment the count of that reference if it has been tracked. If the reference given exists in the structure you created to store references it should return that reference and increment the reference count, otherwise it should return NULL.

void* assign_ref(void* ref);

del_ref() will allow the programmer to specify when they want to decrement the reference count. If the reference count is zero, then the memory needs to be de-allocated and dependencies reference count also decremented. Once a reference has been deallocated the function should return NULL.

void* del_ref(void* ref);

There is no output you need to provide but your functions need to work correctly.

Example 1:

void example() {

  int* m = new_ref(sizeof(int), NULL);

  *(m) = 0;     

  del_ref(m); <-- Deallocated here

}

Example 2:

void example() {

  int* m = new_ref(sizeof(int), NULL);

  int* a = assign_ref(m); <-- Increments count by 1

  *(m) = 2;

  del_ref(m); <-- Decrements

  *a = 0;

  del_ref(a); <-- Deallocates

}

Example 3:

void example() {

  int* m = new_ref(sizeof(int), NULL);

  int* a = new_ref(sizeof(int), m); <-- a is dependent on m

  *(m) = 2;

  del_ref(m); <-- Deallocates m and a

}

Show more
LEARN MORE EFFECTIVELY AND GET BETTER GRADES!
Ask a Question