問題很簡單:給出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