Search code examples
c++linked-listheap-memorydynamic-memory-allocation

Making a pool concept in c++


I have a structure as

struct Employee 
{ 
 char   uName  [255]; 
 struct   Employee *  next; 
 struct   Employee *  prev; 
};

All i want to allocate memory of 100 stucture objects at a time and then use them one by one i making a linked list.If the memory is consumed fully then again i want to allocate 100 object memory

I am doing the allocation as

struct Employee * chunk=new struct Employee[100];

Now when i want to add a new node to a linked list i want to take objects from this already allocated memory.Can somebody tell how to achieve this

Employee * pEmployeeData=NULL;
for(long int i=1;i<=100;i++)
{
        pEmployeeData=EmployeePool+i;
        pEmployeeData->next=NULL;
        pEmployeeData->prev=NULL;
        InsertAtEnd(pEmployeeData);
}

where InsertAtEnd inserts the node at the end of the linked list.Please tell how to achieve this


Solution

  • I would strongly suggest that you don't try to reinvent the wheel by writing your own linked list, instead have a look at the C++ standard library which contains ready-made container types available for you to use. (for example std::vector and std::list).

    Container types exist in the C++ standard library, and are used for storing collections of data/objects. for example, you could do something along the lines of

    #include <iostream>
    #include <vector>
    #include <string>
    
    struct Employee
    {
        std::string name;
        int id;
    };
    
    int main()
    {
        std::vector<Employee> my_employees;
    
        Employee fred = { "Fred", 1 };
        Employee bob = { "Bob", 2 };
    
        my_employees.push_back( fred );
        my_employees.push_back( bob );
    
    
        std::cout << my_employees[0].id << " " << my_employees[0].name << "\n"
                  << my_employees[1].id << " " << my_employees[1].name << std::endl;
    }
    

    The standard containers are easy to use and to learn (You'll find plenty of internet resources which describe how to use them - and your book should also tell you!); If you're new to C++, then it's highly advisable to start out by figuring out how to use these before attempting to create your own.