2013-02-08 25 views
0

問題很簡單:給出start_indexcount,我想看看這些組合是否可以用來安全地訪問一個包含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更有效。或者也許還有其他一些聰明的方法來處理這個問題?

+0

有一長串的方法來檢測事實之前或之後的整數溢出[這裏](http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-cc )。 – Richard

回答

2

您可以通過不同的方式做事有點避免溢出:首先檢查countlength小(保釋出來以其他方式),那麼你可以放心地比較start_index

+0

2人在這裏看不到一個錯誤。來吧,'計數'小於或等於'長度'。 –

+0

如果'length == count',原始代碼(假設沒有溢出問題)將被解救出來。我的建議也會紓解。所以我不相信這裏有一個OBOE。 – Mat

+0

拍攝,你是對的,我把原來的