C語言中的數組索引必須保證位于合法的范圍內!
示例代碼如下:
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類型,可能為負數,這會導致在數組所引用的內存邊界之外進行寫入
解決方案如下:
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;}
新聞熱點
疑難解答
圖片精選