On 2011-12-22, pozz <(E-Mail Removed)> wrote:

> I tried with this...

> size_t left, right, mid;

> if (sizeof(size_t) == 4) {
Right here you are being silly. Don't do this.

I don't know why you keep doing this. Rather than writing something

which is correct on any system, you seem to go out of your way to find

new ways to test for specific systems when they don't matter.

> right = left = 0xFFFFFFFFU;

> mid = (left + right) / 2;

> if (mid == 0x7FFFFFFFU) printf("4: OK\n");

> } else if (sizeof(size_t) == 2) {

> right = left = 0xFFFFU;

> mid = (left + right) / 2;

> if (mid == 0x7FFFU) printf("2: OK\n");

> }

> ...and it prints "4: OK", so it seems there wasn't overflow. Isn't it

> guaranteed by the standard?
This test doesn't even come close to proving what you think it proves. Here's

the thing. Let's ignore all the gratuitous portability problems and imagine

that size_t is 32 bits and has a max of 0xFFFFFFFF. Now, if you do the math,

you'll note:

0xFFFFFFFF + 0xFFFFFFFF = 0xFFFFFFFE. Divide that by two, and

you get 0x7FFFFFFF. Okay, but...

Is that between them?

The goal here is to get a value which is the average of left and right.

Let's make it a bit easier to see.

Let's use:

left = 0xF0000001;

right = 0xF0000003;

The number we want, the average between them, is clearly 0xF0000002. But

what do we get? Well, we probably get (0xE0000004 / 2), which comes out as

0x70000002.

You just carefully wrote a program which proves that there is in fact

overflow, and you're not handling it.

Consider, as an alternative:

mid = ((right - left) / 2) + left;

for size_t, we know that left and right are both always positive, and the

algorithm guarantees that right is never smaller than left. This will

always give you a value between left and right (or, if they're exactly

one apart, equal to left), and will never overflow, and doesn't depend

on guesswork as to the range of size_t. (And there are real systems with

size_t being 8 bytes, which is yet another flaw.)

General Rule: If you are writing logic which uses sizeof() to guess range,

you are almost certainly doing it wrong.

Also, stop and sanity-check your answers. How on earth do you conclude that

7FFFFFFF is the average of two numbers larger than itself?

-s

--

Copyright 2011, all wrongs reversed. Peter Seebach /

http://www.velocityreviews.com/forums/(E-Mail Removed)
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures

http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!

I am not speaking for my employer, although they do rent some of my opinions.