例如以下代码:
1
2
3
4
5
6
7
|
void func( size_t s) { int vla[s]; /*...*/ } /*...*/ func(size); /*...*/ |
解决方案如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
enum {MAX_ARRAY = 1024}; void func( size_t s) { if (s < MAX_ARRAY && s != 0) { int vla[s]; /*...*/ } else { //错误处理 } } /*...*/ func(size); /*...*/ |
2.需要保证复制的目标具有足够的存储空间
参考代码如下所示:
1
2
3
4
5
6
7
8
9
|
enum {WORKSPACE_SIZE = 256}; void func( const int src[], size_t len) { int dest[WORKSPACE_SIZE]; if (len > WORKSPACE_SIZE) { //错误处理 } memcpy (dest, src, sizeof ( int ) * len); /*...*/ } |
3.不要把一个指向非数组对象的指针加上或减去一个整数
错误代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
struct numbers { short num1; short num2; /*...*/ short num9; }; int sum_numbers( const struct numbers *numb) { int total = 0; const int *numb_ptr; for (numb_ptr = &numb->num1; numb_ptr <= &numb->num9; numb_ptr++) { total += *(numb_ptr); } return total; } int main( void ) { struct numbers my_numbers = {1,2,3,4,5,6,7,8,9}; sum_numbers(&my_numbers); return 0; } |
上面的代码试图用指针运算访问结构的元素,这是危险的,因为结构中的字段并不保证在内存中是连续的
解决方案(使用数组)如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
struct numbers { short num1; short num2; /*...*/ short num9; }; int sum_numbers( const short *numb, size_t dim) { int total = 0; const int *numb_ptr; for (numb_ptr = numb; numb_ptr < numb + dim; numb_ptr++) { total += *(numb_ptr); } return total; } int main( void ) { short my_numbers[9] = {1,2,3,4,5,6,7,8,9}; sum_numbers(my_numbers, sizeof (my_numbers) / sizeof (my_numbers[0])); return 0; } |