手机
当前位置:查字典教程网 >编程开发 >C语言 >C语言安全编码之数组索引位的合法范围
C语言安全编码之数组索引位的合法范围
摘要:C语言中的数组索引必须保证位于合法的范围内!示例代码如下:enum{TABLESIZE=100};int*table=NULL;intins...

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

【C语言安全编码之数组索引位的合法范围】相关文章:

c语言 跳台阶问题的解决方法

c语言中用字符串数组显示菜单的解决方法

C语言中宏定义使用的小细节

用c语言根据可变参数合成字符串的实现代码

c语言中数组名a和&a详细介绍

C 语言基础教程(我的C之旅开始了)[九]

c语言调用汇编的方法

C语言宏定义使用分析

C中实现矩阵乘法的一种高效的方法

C语言数组指针的小例子

精品推荐
分类导航