1

I have written following function, it takes a "block" as an argument, searches for the "block" in a list of blocks "lru". Here "block" is an instance of class "Block". Following is the declaration of "lru":

  list<Block> lru;

And following is my search function:

int LRU::searchLRU(Block block)
{
    if (lru.size() == 0) 
    {
        lru.push_back(block);
        return 1;
    }

    list<Block>::iterator i;

    for (i = lru.begin(); i != lru.end(); i++)              
    {
        if (i->get_set() == block.get_set() && i->get_index() == block.get_index()) 
        {
            lru.push_back(block);
            lru.erase(i);
            return 2;
        }
    }

    if (lru.size() == size)
    {
        lru.pop_front();
        lru.push_back(block);
        return 3;
    } 
}

But the problem is sometimes the function returns "0". And as a result of that my overall program is not functioning properly. I feel i have handled all the cases.

Could someone point out the mistake, or why the function returns "0".

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
nish
  • 325
  • 4
  • 9
  • The compiler should've provided you something along the lines of: "*warning: no return statement in function returning non-void*" Unless you turned off warnings. – Floris Velleman Aug 03 '13 at 20:56

1 Answers1

2

The first if covers the empty list case, the last if covers the full list case, the middle for loop cover the not empty not full list but if you don't find the block you will not return from it, so if it's neither full nor empty you'll return 0 by falling off the end of the function. If it wasn't clear, I'll try to rephrase:

empty list -> add item, return 0
full list -> pos item, add item, return 3
partially full list -> find item, *if found* {erase item, add item, return 2}

The problem is if found, if you don't find it, you don't do anything. You'll fall off the end (and that returns 0 in main, is UB otherwise, see here).

Community
  • 1
  • 1
Borgleader
  • 15,826
  • 5
  • 46
  • 62