A bug that almost made me quit my career.

…and there have been many like this.

I try to wrote gooder code, I really do. I am happy to own up to one of my own bugs, but when someone elses’ bug wastes hours or even days of my time, I am … not so happy.

And when “someone else” is whoever wrote the compiler I am using, and it created a bug that defies logic… well, that’s when I blog about it.

Consider this:

unsigned int type = 1;

printf ("Is %u == %u? ", p_tlv_table[table_entry].type, type);

if (p_tlv_table[table_entry].type == type)
{
    printf ("Yes.\r\n");
}
else
{
    printf ("No.\r\n");
}

The table is a structure that contains sets of Type-Length-Value numbers, but that is not important. What is important is that the debug output prints the following:

Is 1 == 1? No.

What if I told you that 1 == 1 is not true?

At the time of the printf, the value of “type” in the table at this entry is 1. It prints 1. It is 1.

And, at the time of the printf, the value of “type” is 1. It prints 1. It is 1.

Yet … the simple “if” fails, reporting that 1 does not equal 1.

This, my friends, is an S.C.T. – Strange Compiler Thing. (I just made that up, but I have been using S.W.T – Strange Window Thing – for way too many years.)

The values in the table are:

typedef struct
{
   uint8_t  type;
   uint8_t  length;
   uint16_t offset; // or uint8_t if not struct is > 255 bytes.
} tlv_offset_entry_t;

So “type” from that table entry is a U8, while “type” in the local variable is an unsigned int. But that should not matter. Test code like this in the same program works as you would expect:

unsigned int val1 = 1;
uint8_t      val2 = 1;

printf ("%u == %u is %d\r\n", val1, val2, (val1 == val2));

That will print 1, indicating that “val1 == val2” was true. They are equal.

So that is not the issue. I mean, you couldn’t do much if you can’t compare variables of different sizes like that.

And if I compare the same structure outside of the function it was passed into, the comparison works as expected.

A compiler quirk strikes again.

And when you can’t check “if (1 == 1)”, this is a good one ;-)

Welcome to my world. (Within minutes of me finally getting code down to be easily reproducible, the company is already working with me to identify why this happens. They rock.)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.