The P-Bug

From Andrey

Revision as of 05:22, 3 February 2006; view current revision
←Older revision | Newer revision→

Original Message-----

From: Potekhin, Andrey Sent: Tuesday, February 01, 2005 10:00 PM To: Dev Hailey Subject: The P-bug



Dear colleagues,

Once in a while people put their names on things that they discover.

We have Rorschach spots, Alzheimer's disease and Eiffel tower.

I would like to introduce

Potekhin's Bug

Put this value into database: 130

Retrieve into char using our usual ADO call: char c = (char)(short)f->Item["MyField"]->Value;

(We need to cast to short since ADO doesn't know how to cast to char directly. Then we need to cast to char to avoid compiler's warning of 'possible loss of data'. Supposed that we are storing values up to 256, we are sure that no data will be lost.)

Unfortunately, the retrieved value, as shown by debugger, is not 130, but -126.

If you think that this is the bug I'm talking about, it is not. You are right, this is just our usual signed/unsigned issue. Since c is declared as a (signed) char, the moment the 1 hits its upper bit it becomes a negative value. This is not a bug - this is how it supposed to be. Bits are all the same. It is still 130 'under the hood'. But keep reading.

Retrieve same value as an int: int i = (short)f->Item["MyField"]->Value;

You guessed correctly, this time the debugger shows 130.

Now, what do you think of this code:

 if (c == i)
 {
    AfxMessageBox("F-word");
 }
 else
 {
     AfxMessageBox("Marijuana");
 } 

Which message will we get? On the one hand, this is -126 vs. 130. On the other:

- Both values have same bits - 10000010, read from the same database field.

- Both are signed values, so no signed/unsigned mismatch here.

- When evaluating the expression, both values are converted to same type, int. So when compared, they are of same size.

Which message will you see? I have to tell you. You're getting the else branch.

This is what we call Potekhin's bug.


Explanation of the trick

You may say, of course, 130 is not -126, period, that's why they don't match. But it does not explain how we end up with such results. I only learned why after looking at bit values in debugger. Compare:

Before conversion to int:

(int) 130 == 10000010 (char) -126 == 10000010

After conversion to int:

(int) 130 == 10000010 (int) -126 == 11111111111111111111111110000010

When a char gets converted, its negative bit gets propagated all the way to the left.

Well, I knew it. Kind of. I knew that it gets propagated. The problem is, I didn't realize that it could lead to scenarios like the described above.

Conclusion? Same old rule. Never use a signed char to store anything above 128. Or if you do, don't compare it then to an int...