前幾天,KOK3客戶端因為我的資源配置錯誤而崩潰了。
調試器帶我到了出錯的代碼行,是一個空指針解引用。
代碼大致如下:
Item* pItem = itemList.getItem(index);
return *pItem;
getItem方法如下:
Item* ItemList::getItem(int index)
{
if (index < 0) return NULL;
if (index >= size()) return NULL;
return _list[index];
}
錯誤是因為資源加載出錯,列表為空,所以getItem()返回NULL.
對于資源加載出錯,應該加載時就提示出錯,不應該在使用時才報錯。
getItem()做了索引越界出錯處理,所以它的調用者必須檢查其返回值。
假設ItemList的指針元素保證不為空,正常情況下,索引正確情況下都不會返回空指針。
這種情況下,添加斷言是必要的。
Item* pItem = itemList.getItem(index);
assert(pItem);
return *pItem;
Item* ItemList::getItem(int index)
{
...
assert(_list[index]);
return _list[index];
}
對與索引值,還是用無符號數為好,可省去下界溢出斷。
調試器帶我到了出錯的代碼行,是一個空指針解引用。
代碼大致如下:
Item* pItem = itemList.getItem(index);
return *pItem;
getItem方法如下:
Item* ItemList::getItem(int index)
{
if (index < 0) return NULL;
if (index >= size()) return NULL;
return _list[index];
}
錯誤是因為資源加載出錯,列表為空,所以getItem()返回NULL.
對于資源加載出錯,應該加載時就提示出錯,不應該在使用時才報錯。
getItem()做了索引越界出錯處理,所以它的調用者必須檢查其返回值。
假設ItemList的指針元素保證不為空,正常情況下,索引正確情況下都不會返回空指針。
這種情況下,添加斷言是必要的。
Item* pItem = itemList.getItem(index);
assert(pItem);
return *pItem;
Item* ItemList::getItem(int index)
{
...
assert(_list[index]);
return _list[index];
}
對與索引值,還是用無符號數為好,可省去下界溢出斷。