r/ProgrammingLanguages • C3 - http://c3-lang.org • May 03 '26

Blog post Unsigned Sizes: A Five Year Mistake

https://c3-lang.org/blog/unsigned-sizes-a-five-year-mistake/
91 Upvotes

115 comments sorted by

View all comments

Show parent comment

2

u/Nuoji C3 - http://c3-lang.org May 09 '26

Interestingly enough, given that you need to check that a signed value is in the interval 0 <= x <= MAX, you only need to check (unsigned)x <= MAX, and usually compilers already optimize for this fact, so you can write it as x >= 0 && x <= MAX without it being two checks.

1

u/EggplantExtra4946 May 09 '26 edited May 09 '26

Interestingly enough, given that you need to check that a signed value is in the interval 0 <= x <= MAX, you only need to check (unsigned)x <= MAX

Not quite. This optimization is only valid if we know that MAX <= INTMAX_MAX. The compiler can know that if MAX is a constant but then this optimization would only apply to fixed-size buffer with a capacity known at compile time. The compiler can not know that in general without interval analysis and possibly more if MAX is variable or expression reading from the heap. A simple optimizer doing only straightfoward dataflow optimizations cannot do this optimization.

If MAX > INTMAX_MAX and INTMAX_MAX < x <= MAX, then (unsigned)x <= MAX is true but we also have (signed)x < 0.

2

u/Nuoji C3 - http://c3-lang.org May 09 '26

I wrote MAX here in capital letters to indicate that it's a constant. If the compiler doesn't do it for you, say you provide it as a constant, then you need to do it manually to get rid of the comparison yes.

1

u/EggplantExtra4946 May 09 '26 edited May 09 '26

As you can see, neither GCC nor LLVM Clang can perform that optimization with -O3 when MAX is not known at compile time.

https://godbolt.org/z/hcs4a1o16

https://godbolt.org/z/WMr7cMqc3

If I use 4096 instead of array->length, your optimization is peformed but so what? Almost nothing except I/O buffers is going to use a fixed-size array of capacity known at compile time, and even those might use a capacity that can be modfied at runtime, so effectively this optimization will be performed rarely and almost all properly done bounds checks involving signed indexes will require 2 conditionals.

1

u/Nuoji C3 - http://c3-lang.org May 10 '26

Well, that certainly depends. The C3 stdlib uses a lot of interval checks with a known max value when checking size parameters. This is for robustness, since often you have code that is written for some int type, allowing it to have values up to UINT_MAX / INT_MAX. But taking into account calculations, it's not safe to use such large numbers.

The lack of max value checks is incidentally a big cause of vulnerabilities.