当前位置:首页 > 未命名 > 正文

C语言中的数组索引必须保证位于合法的范围内!

示例代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 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类型,可能为负数,这会导致在数组所引用的内存边界之外进行写入

解决方案如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 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; }
如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。