A killer novice bug

Recently I had ‘one of those moments’ in my CP1 lab. I am a little embarrassed to say that I spent the last few minutes of this session staring at a C function written by a student that wasn’t behaving the way it should. The students were asked to write a function that returns max value stored in a stack. Below is a reconstruction of the student’s code, slightly simplified:

int max(Stack *sptr) {
    int max = INT_MIN;
    Node popped;
    while (!isEmpty(sptr)){
         popped = pop(sptr);
         if(popped->data > max);{
             max = popped->data;
         }
    }
    return max;
}

The symptom of the bug was that the value of max returned was always the value of the last item popped from the stack.

A few labs later I had a similar situation. This time I spotted the bug right away (and embarrassingly felt slightly proud).

I am going to hope that at this point there are two types of people reading this:

  1. those that see the bug immediately
  2. those that don’t

For selfish reasons I hope that there are at least a few 2’s. At the time I had just written my own solution to this question, and had helped a dozen other students with their versions of their solutions. Needless to say that running up to the 90 minute mark I was suffering from code blindness. At least that’s my excuse for not seeing the error immediately.

So, for all of you 2’s out there, if there are any, the bug is the empty statement after the if condition. I have to say I sensed a mixture of relief and disappointment from the student when I pointed out the bug and her output was now as expected. The relief was coming from obvious places, but the disappointment seemed to stem from a sense of ‘Really? That’s it? You have got to be kidding me.’. I have to say I did feel for her.

A few days later in lecture I wrote the above code on the board (in China we are still using good-old-fashioned chalk and chalkboards), and asked the 100+ students to point out the problem. It took a good two minutes for the first student to do so.

gcc (4.9.3, no options) gives no warning for empty statements. I just checked Java SE 8 update 92, which gives an empty statement after if warning, which despite my unhappiness with most have compiler error messages, is quite nice.

I think next year I’ll spend a little time discussing the empty statement and NOPs, as early as possible, and see if that reduces the troubles experienced this year.

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s