服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C语言安全编码之数组索引位的合法范围

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

2021-01-21 13:57C语言程序设计 C/C++

这篇文章主要介绍了C语言安全编码的数组索引位合法范围剖析,对于编码安全非常重要!需要的朋友可以参考下

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

延伸 · 阅读

精彩推荐