问题很简单:给出start_index
和count
,我想看看这些组合是否可以用来安全地访问一个包含length
元素的数组。我有暂时如下:绑定检查和整数溢出
uint32_t start_index = (value from somewhere);
uint32_t count = (value from somewhere);
uint32_t length = (value set earlier);
char *array = (memory allocated earlier);
if(start_index + count < length) {
// access array starting at start_index
} else {
// bailout
}
的检查,当然,不足之处,因为start_index + count
可以超过一个uint32_t的最大可能值,并绕到小值。为了解决这个问题,我想知道将变量提升到64位还是置于第二个条件start_index + count > start_index
更有效。或者也许还有其他一些聪明的方法来处理这个问题?
有一长串的方法来检测事实之前或之后的整数溢出[这里](http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-cc )。 – Richard