These sorts of bugs seem like an inherent side effect of implicitness, in this case of implicit type casting in C/C++. Rust mostly solves this specific class of bugs by requiring explicit type casts. As a consequence, in Rust, unlike in C/C++, it is idiomatic to use an unsigned integer when negative values are semantically invalid.<p>Rust also makes it fairly easy to define a `newtype` wrapper, for when you need semantics different from the primitive types. You can, for example, define an integer wrapper that always panics on overlow (as opposed to only in debug builds, which is the default for Rust). Recently, I've used this pattern to define a networking "sequence number" type that does not implement ordering operators (less than, greater than, etc.), but instead provides `older_than`, `newer_than`, etc. I made the switch after correcting multiple bugs caused by implicit and incorrect assumptions of total ordering; making the switch uncovered several more of such bugs . Of course, such a pattern is possible in C/C++ as well, but it is not as ergonomic and thus not as common.
> Unsigned int should be used instead of int for "num", but many programmers use int as a generic type for everything.<p>Yes, this is very common. For example, Google requires that C++ code always uses int instead of unsigned.
Interesting; I'll have to takea closet look at <a href="https://yurichev.com/writings/SAT_SMT_by_example.pdf" rel="nofollow">https://yurichev.com/writings/SAT_SMT_by_example.pdf</a>.<p>If you've heard of Frama-C, these issues are highlighted by automatically inserted checks.
<i>malloc() will crash on too big input value, because malloc() takes unsigned size_t on input.</i><p>Will it, or will it just fail and return null (which may crash later code if it doesn't check)? I believe the spec mandates the latter.
While C integer rules are bit too arcane for me to remember, isn't the conversion from unsigned to signed integer in __addvsi3 undefined if the sum is greater than INT_MAX? If it is, the whole function is pretty much useless as compiler can optimize it to just plain addition.