为什么无符号整数容易出错? [英] Why are unsigned integers error prone?
问题描述
我在观看此视频。 Bjarne Stroustrup 说,无符号整数容易出错,并导致错误。所以,你应该只使用它们,当你真的需要它们。我也读过Stack Overflow的一个问题(但我不记得哪一个),使用 unsigned ints 会导致安全漏洞。
它们如何导致安全漏洞?有人可以通过给出适当的例子来清楚地解释它吗?
一个可能的方面是无符号整数可能导致循环中有些难以解决的问题,因为下溢导致大数。我不能计数(即使使用无符号整数!)多少次我做了这个bug的变体
for(size_t i = foo.size(); i> = 0; --i)
...
注意,根据定义, i> = 0
总是为真。 (这首先是什么原因是如果 i
被签名,编译器将警告有可能的溢出与 size_t $ c $
I was looking at this video. Bjarne Stroustrup says that unsigned ints are error prone and lead to bugs. So, you should only use them when you really need them. I've also read in one of the question on Stack Overflow (but I don't remember which one) that using unsigned ints can lead to security bugs.
How do they lead to security bugs? Can someone clearly explain it by giving an suitable example?
One possible aspect is that unsigned integers can lead to somewhat hard-to-spot problems in loops, because the underflow leads to large numbers. I cannot count (even with an unsigned integer!) how many times I made a variant of this bug
for(size_t i = foo.size(); i >= 0; --i)
...
Note that, by definition, i >= 0
is always true. (What causes this in the first place is that if i
is signed, the compiler will warn about a possible overflow with the size_t
of size()
).
There are other reasons mentioned Danger – unsigned types used here!, the strongest of which, in my opinion, is the implicit type conversion between signed and unsigned.
这篇关于为什么无符号整数容易出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!