C語言中的數(shù)組索引必須保證位于合法的范圍內(nèi)!
示例代碼如下:
enum {TABLESIZE = 100};int *table = NULL;int insert_in_table(int pos, int value) { if(!table) { table = (int *)malloc(sizeof(int) *TABLESIZE); } if(pos >= TABLESIZE) { return -1; } table[pos] = value; return 0;}
其中:pos為int類型,可能為負(fù)數(shù),這會(huì)導(dǎo)致在數(shù)組所引用的內(nèi)存邊界之外進(jìn)行寫入
解決方案如下:
enum {TABLESIZE = 100};int *table = NULL;int insert_in_table(size_t pos, int value) { if(!table) { table = (int *)malloc(sizeof(int) *TABLESIZE); } if(pos >= TABLESIZE) { return -1; } table[pos] = value; return 0;}
|
新聞熱點(diǎn)
疑難解答
圖片精選