Question

The object manager's interface is given by the file ObjectManager.h and the implementation will be in...

The object manager's interface is given by the file ObjectManager.h and the implementation will be in the file ObjectManager.c. Your task is to implement the functions required for the object manager. This includes all the functions listed in ObjectManager.h.

#ifndef _OBJECT_MANAGER_H
#define _OBJECT_MANAGER_H

#ifndef MEMORY_SIZE
#define MEMORY_SIZE 1024*512
#endif

#define NULL_REF 0

typedef unsigned long Ref;


// This function trys to allocate a block of given size from our buffer.
// It will fire the garbage collector as required.
// We always assume that an insert always creates a new object...
// On success it returns the reference number for the block of memory allocated for the object.
// On failure it returns NULL_REF (0)
Ref insertObject( const int size );

// returns a pointer to the object being requested given by the reference id
void *retrieveObject( const Ref ref );

// update our index to indicate that we have another reference to the given object
void addReference( const Ref ref );

// update our index to indicate that a reference is gone
void dropReference( const Ref ref );

// initialize the object manager
void initPool();

// clean up the object manager (before exiting)
void destroyPool();

// This function traverses the index and prints the info in each entry corresponding to a block of allocated memory.
// You should print the block's reference id, it's starting address, and it's size (in bytes).
void dumpPool();

#endif
0 0
Add a comment Improve this question Transcribed image text
Answer #1

main.c


#include <stdio.h>
#include "ObjectManager.h"

int main(int argc, char *argv[])
{
    char *ptr;
    int i;
    Ref id1, id2, id3;
    initPool();
  
    id1 = insertObject(1020);
    ptr = (char*)retrieveObject(id1);
    for (i = 0; i < 1020; i++)
        ptr[i] = (char)(i%26 + 'A');
  
    id2 = insertObject(4);
    ptr = (char*)retrieveObject(id2);
    for (i = 0; i < 4; i++)
        ptr[i] = (char)(i%26 + 'H');
  
    dropReference(id2);
  
    id3 = insertObject(3);
    dropReference(id3);
    id3 = insertObject(12);
    ptr = (char*)retrieveObject(id3);
    for (i = 0; i < 12; i++)
        ptr[i] = (char)(i%26 + 'O');
  
    ptr = (char*)retrieveObject(id1);
    for (i = 0; i < 30; i++)
        fprintf(stderr,"%c",ptr[i]);
    fprintf(stderr,"\n");
  
    dumpPool();
    dumpPool();
    destroyPool();
    fprintf(stderr,"---\n");
    return 0;
}

ObjectManager.h


#ifndef _OBJECT_MANAGER_H
#define _OBJECT_MANAGER_H

// The number of bytes of memory we have access to -- put here so everyone's consistent.
#ifndef MEMORY_SIZE
#define MEMORY_SIZE 1024*512
#endif

#define NULL_REF 0

typedef unsigned long Ref;

Ref insertObject( const int size );

// returns a pointer to the object being requested given by the reference id
void *retrieveObject( const Ref ref );

// update our index to indicate that we have another reference to the given object
void addReference( const Ref ref );

// update our index to indicate that a reference is gone
void dropReference( const Ref ref );

// initialize the object manager
void initPool();

// clean up the object manager (before exiting)
void destroyPool();

// This function traverses the index and prints the info in each entry corresponding to a block of allocated memory.
// You should print the block's reference id, it's starting address, and it's size (in bytes).
void dumpPool();

// Mark and Sweep Defragmenting garbage collector
static unsigned long compact();
#endif

ObjectManager.c

#include "ObjectManager.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

typedef struct Index index_item;

struct Index
{
    Ref ID;       // number of the object in pool
    void *start; // pointer to the object
    int size;     // size of object in bytes
    unsigned int refCount;   // number of references currently in use
    index_item *next; // pointer to the next index_item, NULL if the last
};

#define poolSize 1024

//-------------------------------------------------------------------------------------
// FILE-SCOPE VARIABLES
//-------------------------------------------------------------------------------------

// pools of objects in the heap
void *pool[2] = {NULL, NULL};
int active_pool = 0;

// pointer to the first index_item
index_item *top = NULL;
index_item *last = NULL;

// number of currently created objects
int objectCount = 0;

// pointer to the beginning of the next unused address
void *freePtr = NULL;


//-----------------------------------------------------------------------------
// IMPLEMENTATION
//-----------------------------------------------------------------------------

index_item *createIndexItem (const int size)
{
    index_item *newindex_item = malloc (sizeof (index_item));
  
    assert (newindex_item != NULL);

    if (newindex_item)
    {
        newindex_item->ID = ++objectCount;
        newindex_item->refCount = 1;
        newindex_item->size = size;
        newindex_item->next = NULL;
    }
    return newindex_item;
}

// search for given number, return pointer to index_item if found or NULL otherwise
index_item *searchIndex (const Ref ref)
{
    index_item *ind = top;
    while ( (ind) && (ind->ID != ref) )
        ind = ind->next;
    return ind;
}


void removeIndexItem (const Ref ref)
{
    index_item *ind = top;
    index_item *prev = top;
    while ( (ind) && (ind->ID != ref) )
    {
        prev = ind;
        ind = ind->next;
    }
    prev->next = ind->next;
    free(ind);
}


Ref insertObject (const int size)
{
    Ref result = NULL_REF;
    index_item *newindex_item = createIndexItem (size);
  
    unsigned long memAvailable = pool[active_pool] + poolSize - freePtr;
  
    // if not enough memory, try to GC the pool and check again
    if ( (memAvailable < size) && (memAvailable + compact() < size) )
        return NULL_REF;
    else if (newindex_item)
    {
        if (!top)
            top = newindex_item;
        else
            last->next = newindex_item;
        last = newindex_item;
        newindex_item->start = freePtr;
        freePtr += size*sizeof(char);
        result = newindex_item->ID;
    }
  
//    assert ( ((result == true) && (newindex_item != NULL)) || (result == false && newindex_item == NULL) );
//    assert (search(item));
  
    return result;
}


void *retrieveObject (const Ref ref)
{
    void *result = NULL;
    index_item *ind = searchIndex (ref);
  
    if (ind)
        result = ind->start;
    return result;
}


void addReference (const Ref ref)
{
    index_item *ind = searchIndex (ref);
    if (ind)
        ind->refCount++;
}


void dropReference (const Ref ref)
{
    index_item *ind = searchIndex (ref);
    if (ind && (ind->refCount > 0))
        ind->refCount--;
}


void initPool()
{
    pool[0] = malloc(sizeof(char)*poolSize);
    pool[1] = malloc(sizeof(char)*poolSize);
    freePtr = pool[0];
}


void destroyPool()
{
    if (top)
    {
        index_item *temp = NULL;
      
        while (top != NULL)
        {
            temp = top;
            top = top->next;
            free (temp);
            objectCount--;
        }
        top = NULL;
    }
    free (pool[0]);
    free (pool[1]);
    assert (objectCount == 0);
}

void dumpPool()
{
    index_item *ind = top;
    unsigned long offset = 0;
  
    printf ("\n==================================");
    printf ("\n|         Pool information:       |");
    printf ("\n==================================\n");
    while (ind)
    {
        assert ( pool[active_pool] + offset == ind->start );
        offset += ind->size;
        printf ("\nID:    %lu\nStart: %#011x\nSize: %d\n", ind->ID, (unsigned)ind->start, ind->size);
        ind = ind->next;
    }
}


static unsigned long compact()
{
    unsigned long memFreed = 0;
    index_item *ind = top;
    freePtr = pool[!active_pool];
    while (ind)
    {
        if (ind->refCount)
        {
            memcpy(freePtr, ind->start, ind->size);
            ind->start = freePtr;
            freePtr += ind->size;
        }
        else
        {
            memFreed += ind->size;
            removeIndexItem(ind->ID);
            objectCount--;
        }
        ind = ind->next;
    }
    active_pool = !active_pool;   //toggle
    return memFreed;
}

Add a comment
Know the answer?
Add Answer to:
The object manager's interface is given by the file ObjectManager.h and the implementation will be in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please do it carefully Using the header file ( MyArray.h ) Type the implementation file MyArray.cpp,...

    Please do it carefully Using the header file ( MyArray.h ) Type the implementation file MyArray.cpp, and a test file to test the functionality of the class. Hint: read all the explanations in the header with attention. MyArray.h : #ifndef MYARRAY_H #define MYARRAY_H #include <iostream> using namespace std; class MyArray { friend ostream& operator<<( ostream & output, const MyArray & rhs); // to output the values of the array friend istream& operator>>( istream & input, MyArray & rhs); // to...

  • write the interface of the following functions in the SortedArray.cpp, by the given functions in the SortedArray.h : #if...

    write the interface of the following functions in the SortedArray.cpp, by the given functions in the SortedArray.h : #ifndef SortedArray_H #define SortedArray_H //INCLUDES #include <iostream> using namespace std; //---------------------------------- // SortedArray<Object> //---------------------------------- template <typename Object> class SortedArray { public: /** insert param: obj Description: insert new elements into the correct position in the sorted array, sliding elements over the position to right, as needed    */    void insert(const Object &obj);    /**    Description: remove the element in position 0, and slide over...

  • QUESTION: ADT stack: resizable array-based implementation    for Ch4 programming problem 4 "maintain the stacks's top...

    QUESTION: ADT stack: resizable array-based implementation    for Ch4 programming problem 4 "maintain the stacks's top entry at the end of the array" at array index N-1 where the array is currently allocated to hold up to N entries. MAKE SURE YOU IMPLEMENT the functions:  bool isEmpty() const; bool push(const ItemType& newEntry); bool pop(); in ArrayStackP4.cpp //FILE StackInterface.h #ifndef STACK_INTERFACE_ #define STACK_INTERFACE_ template<class ItemType> class StackInterface { public:    /** Sees whether this stack is empty.    @return True if the...

  • #ifndef HEAP_H_ #define HEAP_H_ namespace cse { template<typename dtype> class heap { public: /** TO DO::...

    #ifndef HEAP_H_ #define HEAP_H_ namespace cse { template<typename dtype> class heap { public: /** TO DO:: default constructor perform new to reserve memory of size INITIAL_CAPACITY. set num_items = 0; */ heap() { // write your code here }; /** Create a heap from a given array */ heap(dtype *other, size_t len) { // write your code here }; /** copy constructor copy another heap to this heap. */ heap(const heap<dtype> &other) { //write your code here }; /** Accessor...

  • Needed in C please Write the implementation file, priority_queue.c, for the interface in the given header file, priority_queue.h. Turn in your priority_queue.c file and a suitable main program, main.c...

    Needed in C please Write the implementation file, priority_queue.c, for the interface in the given header file, priority_queue.h. Turn in your priority_queue.c file and a suitable main program, main.c, that tests the opaque object. priority_queue.h is attached as a file to this assignment but is also listed here for your convenience. Your implementation file should implement the priority queue using a heap data structure. Submissions that implement the priority queue without using a heap will not receive any credit. #ifndef...

  • Files given in this assignment (right-click on the file to download) Assignment7.cpp (need to complete) Student.h...

    Files given in this assignment (right-click on the file to download) Assignment7.cpp (need to complete) Student.h (Given. Just use it, don't change it!) Student.cpp (Partially filled, need to complete) 1. Assignment description In this assignment, you will write a simple class roster management system for ASU CSE100. Step #1: First, you will need to finish the design of class Student. See the following UML diagram for Student class, the relevant header file (class declaration) is given to you as Student.h,...

  • -------c++-------- The Passport class takes a social security number and the location of a photo file. The Passport class has a Photo class member, which in a full-blown implementation would store the...

    -------c++-------- The Passport class takes a social security number and the location of a photo file. The Passport class has a Photo class member, which in a full-blown implementation would store the passport photo that belongs in that particular passport. This Photo class holds its location or file name and the pixel data of the image. In this lab the pixel data is only used to show how memory maybe used when a program uses large objects. We will not...

  • My main() file does not call to the class created in a .hpp file. It comes...

    My main() file does not call to the class created in a .hpp file. It comes out with the error "undefined reference to "___" const. I want to solve this by only changing the main() .cpp file, not the .hpp file. .cpp file .hpp file Thank you! include <iostream> include <string> tinclude "CourseMember.hpp using namespace std int main0 CourseMember CourseMember(90, "Jeff", "Goldblum"): // initializing the constructor cout<< "Member ID is <<CourseMember.getID) << endl; 1/ calling getID) accessor cout <<"First Name...

  • C++ problem to use dynamic memory allocation (of arrays) and pointer manipulation in order to implement...

    C++ problem to use dynamic memory allocation (of arrays) and pointer manipulation in order to implement the Inner and Outer classes (Circular Buffer of circular buffers using Queues). No need of any classes from the Standard Template Library (STL), not even vector. Add the member functions of those classes by following the codes of InnerCB.h and CBofCB.h below: // file: InnerCB.h // Header file for Inner Circular Buffer. // See project description for details. // #ifndef _INNERCB_H_ #define _INNERCB_H_ class...

  • Write a C++ program that includes the following: Define the class Student in the header file Stu...

    Write a C++ program that includes the following: Define the class Student in the header file Student.h. #ifndef STUDENT_H #define STUDENT_H #include <string> #include <iostream> using namespace std; class Student { public: // Default constructor Student() { } // Creates a student with the specified id and name. Student(int id, const string& name) { } // Returns the student name. string get_name() const { } // Returns the student id. int get_id () const { } // Sets the student...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT