Find the Bug - I

White box testing is not about finding obvious cases which any way will be caught during the Black box testing, but its about finding the rare cases where the software will break. Finding the cases where the software breaks by inspecting the code is always challenge. Here, I am adding a code snippet which has a bug, lets see how many testers can identify such bugs:


.............
int num=10;
ArrayList FullList = GetObjectsList();
ArrayList RandList = new ArrayList(num);
Random rand = new Random();
int index;
int maximum = FullList.Count;
int max_objs = (num > FullList.Count) ? FullList.Count : num;
while(RandList.Count < max_objs)
{
index = rand.Next(1, maximum);
//This returns rand value between 1 and maximum-1 (both inclusive)
if(!RandList.Contains(FullList[index]))
RandList.Add(FullList[index]);
}
.............

The code snippet is about getting 10 or less random objects from a list of objects. Under which scenario the code can be disastrous ? Add your solution to the comments.

7 comments:

  1. hi ,
    Shudn't the condition read as Randlist.Count-1,otherwise out of bound exception will be given.

    Also I am a bit doubtful about the
    Randlist.Count's value even if u put Randlist.Count-1 in the logic,as their seems to be no way by which u can reduce the count,so that the while loop stops some where.But I could be wrong there.

    ReplyDelete
  2. Anonymous7:37 AM

    Question:
    What is r.Next ?
    Is it rand.Next?

    ReplyDelete
  3. Anonymous11:42 AM

    Hi, there is the following problem:
    you defined:
    index = rand.Next( 1, maximum);
    which is not the best solution as you use the index on a zero based collection. So if your method GetObjectsList returns for example 3 objects, you can't fill up the collection RandList completly. You have to define:
    index = rand.Next(0, maximum)
    to do this job. Otherwise your condition will be a neverending story :)

    ReplyDelete
  4. Ketan, Randlist.Count is fine and we dont need Randlist.Count-1 as we are using < in while condition and not <=

    Anonymous, thanks for pointing the mistake, made the change in the post.

    Norbert, COngrats for finding the exact bug which pushes the code into infinite loop

    ReplyDelete
  5. Anonymous1:31 PM

    Thank you. This wasn't a difficult thing :)

    ReplyDelete
  6. Hi Malik,

    As a tester, I am more interested to understand "Are there any bugs, that cannot be found in black box testing, that can only be found during white box testing?

    ReplyDelete
  7. Pradeep, if the blackbox testing is done throughly with all proper test cases then you may not miss any bugs. Basically white box testing helps in early identification of the bugs and also easily coming up with the rare test cases wherein the code might fail.

    ReplyDelete