3 ms·
> you would only be able to have an element size of 1 byte Yes, when people point out this bug, it seems crazy. Who does a binary search of 1GB of sorted data
by civility 8y ago
> you would only be able to have an element size of 1 byte
Yes, when people point out this bug, it seems crazy. Who does a binary search of 1GB of sorted data which only contains values from 0...255 (or -128...127). I mean it is a bug, but it's also the wrong data structure for that data...
> to use a 32-bit element count on a 64-bit system is itself a more valid bug
Yes, this one is real. Even ignoring the binary search algorithm, I cringe whenever I see people use "int" as a loop index. 2 gig arrays were very common in the work I used to do.
I also cringe when I see people used unsigned (size_t) loop indices, but that's a deeper topic.
- asalahli 8y agoI'm curious, what's wrong with size_t loop indices? I always thought that was the most correct type for the job
- civility 8y agoIt's fine until you do almost any arithmetic using the index. Unsigned arithmetic is rarely what you want, and it quietly converts all of your signed types to unsigned giving you large positive values instead of small negative ones. Maybe this isn't a common use case for most people, but it came up all the time when I was doing signal processing algorithms. Using ssize_t is pretty reasonable, and you're not going to overflow ssize_t for loop indices except in some very pathological cases on a 32 bit architecture. If the arithmetic argument doesn't convince you, here's another one: write a correct loop (using size_t) which traverses your array in reverse order. Here is a broken example which would be fine with ssize_t: for (size_t ii = len - 1; ii >= 0; --ii) { }
- drobi 8y agoCan you not do: for (size_t i = len-1; i < len; i--)? Isn't -1 defined to be the largest integer that the unsigned type can handle? Edit: I guess that wasn't the point of your example (that it may not be easily recognisable as a bug?)
- civility 8y agoYeah, that works, but it's going to confuse more than half the people who ever look at it.
- mnaydin 8y agoA modern compiler would warn about the condition (ii >= 0) being always true. One correct way would be for (size_t i = len; i > 0; --i) { // use i-1 as the array index } or, size_t i = len while (i-- > 0) { // use i as the array index }