0

Hi i am programming a mock operating system for a class and am trying to use the best fit allocation technique to allocate memory for the processes. my list has two parameters a num_units and a process_id there are 128 units to start and process id is -1 if my program searches and finds a -1 it then compares the num of units and inserts a new Node into the list if it will fit. i keep running into the problem of it only allocating 3 or 4 items out of 10,000 simulated here is the allocate function

int allocate_mem(int process_id, int num_units)
{
    list<Node>::iterator best = memory_list.begin();

    // TODO: Implement
     for(list<Node>::iterator cur = memory_list.begin(); cur != memory_list.end(); ++cur)
     {
        if (cur->process_id == HOLE_PROCESS_ID)  
        {
            if (cur->num_units == num_units)
            {
                cur->process_id = (process_id);
                num_alloc_successes++;
                return temp;               
            }

            else if (cur->num_units > num_units)
            {
                if (best->num_units > cur->num_units)
                {
                    best = cur;
                }
            }  
         }
        temp++;
     }
    if (best->num_units > num_units)
    {
        best->num_units = (best->num_units - num_units);
        memory_list.insert(best,1,Node(process_id, num_units));
        num_alloc_successes++;
        return temp;
    }

    ++num_alloc_failures;
    return -1;
}

there is also a deallocate function that seems to be working correctly

thanks in advance for you help.

R Sahu
  • 204,454
  • 14
  • 159
  • 270

1 Answers1

0

First, the only way to exit the for loop early is to hit an exact match.

Second, best keeps getting set to cur as long as cur->num_units > num_units, so that winds up being the last element in the list that meets that requirement.

Third, you're not splitting your partially used blocks properly. I am pretty sure you are destroying information. In fact, you do not seem to have any means to merge memory blocks. Are you sorting your list by size?

jwdonahue
  • 6,199
  • 2
  • 21
  • 43