源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C语言安全编码之数组索引位的合法范围

  • 时间:2022-08-05 15:31 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C语言安全编码之数组索引位的合法范围
[b]C语言中的数组索引必须保证位于合法的范围内! [/b]示例代码如下:
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;
}

其中:[b]pos为int类型,可能为负数,这会导致在数组所引用的内存边界之外进行写入[/b] 解决方案如下:
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;
}
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部