6 ms·
Please explain how a string length would need more than size_t to represent it.
by djmdjm 14y ago
Please explain how a string length would need more than size_t to represent it.
- adobriyan 14y agoThis is largely theoretical but still. Smart programming languages have bignum integers and seamless promotion between fixnum and bignum versions. Thus they avoid the issue completely, no stupid casts (especially casts which change both signedness and size), no overflows, no nothing, just an integer length. It's a perfect world and everyone should try to achieve it. C is not such programming language, with the closest approximation being uintmax_t. size_t is of course enough in practice.
- wladimir 14y agoEven for fixnums, integer overflows and underflows of any kind should ideally result in an exception by default. I think it's a pity that C(++) doesn't have support for this. A lot of bugs and weaknesses could have been prevented (for example, CWE 680 http://cwe.mitre.org/data/definitions/680.html http://cwe.mitre.org/data/definitions/680.html). I know this decision (to simply wrap around in the case of an over/underflow) was probably performance-driven, but on the other hand, if the common languages had required it, CPUs would have better support for it... Edit: Some googling shows that Microsoft has a SafeInt class in common use that reports under/overflow: http://safeint.codeplex.com/ http://safeint.codeplex.com/ . Still it feels like a kludge for this to be not part of the main language.
- JoachimSchipper 14y ago(Hint: gcc has a -ftrapv option, which traps on signed integer overflow. Unsigned overflow is defined, so trapping on that would break working code.)
- wladimir 14y agoI don't think I'd necessarily want to trap on all (signed) integer overflows. As you say, it might break working code. There's just too much C/C++ code around to change that retroactively. And for modular arithmetic and such it is desirable for integers to wrap around. But a "trap on overflow" signed and unsigned int type would be nice.
- JoachimSchipper 14y agoRecent gcc versions use the fact that signed overflow is undefined to do some unexpected optimizations (in particular, a + b < a will never be true if a, b are ints.) I don't think -ftrapv is going to cause many additional errors, but I haven't actually tried it. (Also, http://embed.cs.utah.edu/ioc/ http://embed.cs.utah.edu/ioc/ looks interesting.)
- Natsu 14y ago> (in particular, a + b < a will never be true if a, b are ints.) Code of exactly that form in the patch for this bug made me do a double take. Fortunately, they'd also changed the a & b from plain ints to size_t, so it was ok.