欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C語(yǔ)言安全編碼之?dāng)?shù)組索引位的合法范圍

 更新時(shí)間:2014年07月07日 12:12:24   投稿:shichen2014  
這篇文章主要介紹了C語(yǔ)言安全編碼的數(shù)組索引位合法范圍剖析,對(duì)于編碼安全非常重要!需要的朋友可以參考下

C語(yǔ)言中的數(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類(lèi)型,可能為負(fù)數(shù),這會(huì)導(dǎo)致在數(shù)組所引用的內(nèi)存邊界之外進(jìn)行寫(xiě)入

解決方案如下:

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;
}

相關(guān)文章

最新評(píng)論