C语言安全编码之数组索引位的合法范围
C语言中的数组索引必须保证位于合法的范围内!
示例代码如下:
enum{TABLESIZE=100};
int*table=NULL;
intinsert_in_table(intpos,intvalue){
if(!table){
table=(int*)malloc(sizeof(int)*TABLESIZE);
}
if(pos>=TABLESIZE){
return-1;
}
table[pos]=value;
return0;
}
其中:pos为int类型,可能为负数,这会导致在数组所引用的内存边界之外进行写入
解决方案如下:
enum{TABLESIZE=100};
int*table=NULL;
intinsert_in_table(size_tpos,intvalue){
if(!table){
table=(int*)malloc(sizeof(int)*TABLESIZE);
}
if(pos>=TABLESIZE){
return-1;
}
table[pos]=value;
return0;
}
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短