3 ms·
Here's some code you can compile, it shows the problem: #include <stdio.h> #include <stdint.h> int main() { printf("size_t bytes: %u\n", sizeof(si
by pishpash 9y ago
Here's some code you can compile, it shows the problem:
#include <stdio.h>
#include <stdint.h>
int main() {
printf("size_t bytes: %u\n", sizeof(size_t));
size_t high = SIZE_MAX;
size_t low = high-1;
size_t mid_correct = low+(high-low)/2;
size_t mid_incorrect = (low+high)/2;
printf("low: %.ju\n", low);
printf("high: %.ju\n", high);
printf("low+high: %.ju\n", low+high);
printf("(low+high)/2 -- incorrect: %.ju\n", mid_incorrect);
printf("low+(high-low)/2 -- correct: %.ju\n", mid_correct);
}
On my 64-bit machine, I get:
size_t bytes: 8
low: 18446744073709551614
high: 18446744073709551615
low+high: 18446744073709551613
(low+high)/2 -- incorrect: 9223372036854775806
low+(high-low)/2 -- correct: 18446744073709551614
- SAI_Peregrinus 9y agoThis is a great illustration of the actual bug.