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;
}
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下