【C语言】数组越界

1. 越界

1.1 静态数组越界

在C语言中,我们可以直接通过数组索引来访问数组中的元素。如果一个数组有 n 个元素,对这 n 个元素(索引从 0n-1 的元素)的访问都合法,如果对这 n 个元素之外的访问,就是非法的,称为越界(access out of range),例如:

#include <stdio.h>

#define SIZE 5

int main(int argc, char *argv[]) {
	int array[SIZE] = {0};
	unsigned index = 0;

	for (index = 0; index <= SIZE; index++) {
		printf("[%u] = %d\n",
				index, array[index]);
	}
	
	return 0;
}
/* The end of source file that named 'main.c' */

输出:

[0] = 0
[1] = 0
[2] = 0
[3] = 0
[4] = 0
[5] = 32766	#error overflow

有上面的输出就说明它并不会造成编译错误! 因为C语言的编译器并不会判断你的代码访问越界了。错误就这样通过编译了。
数组访问出现越界,结果是不可预测(可能导致程序崩溃、安全漏洞或其他不可预测的行为)。有时什么事也没有,程序一直运行(某些错误可能已经存在);有时则是程序崩溃。因此,在使用数组时一定要判断是否越界以保证程序的正确性。

1.2 动态数组越界

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

typedef struct coordinate {
    int x;
    int y;
} Coordinate;

int main(int argc, char *argv[]) {
    /*
     * Set an array that the size is 5.
     */
    Coordinate *array = calloc(SIZE, sizeof(Coordinate));
    /*
     * The index is used to loop.
     */
    unsigned index = 0;

    for (index = 0; index < SIZE * 2; index++) {
        printf("[%u]=(%d, %d)\n",
                index,
                array[index].x,
                array[index].y);
    }

    free(array);
    array = NULL;

    return 0;
}
/* The end of source file */

编译后输出:

[0]=(0, 0)
[1]=(0, 0)
[2]=(0, 0)
[3]=(0, 0)
[4]=(0, 0)
[5]=(0, 0)
[6]=(0, 0)
[7]=(0, 0)
[8]=(0, 0)
[9]=(0, 0)

可以看到申请的内存长度为 SIZE = 5,但是循环输出次数为 SIZE * 2存在逻辑错误却可以编译执行,还不会报错。 其是错误已经发生了。

相关推荐

  1. C语言数组越界

    2024-04-10 11:42:05       35 阅读
  2. C++访问越界

    2024-04-10 11:42:05       27 阅读
  3. C/C++内存越界的常有例子

    2024-04-10 11:42:05       39 阅读
  4. QT (C++)定位内存越界(踩内存)问题

    2024-04-10 11:42:05       45 阅读
  5. C语言数组语法解剖

    2024-04-10 11:42:05       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-10 11:42:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-10 11:42:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-10 11:42:05       82 阅读
  4. Python语言-面向对象

    2024-04-10 11:42:05       91 阅读

热门阅读

  1. c#防呆设计

    2024-04-10 11:42:05       37 阅读
  2. uniapp_微信小程序_NaN

    2024-04-10 11:42:05       35 阅读
  3. python中tkinter窗口内替换鼠标图标

    2024-04-10 11:42:05       34 阅读
  4. 【linux】cp命令介绍以及使用范例

    2024-04-10 11:42:05       34 阅读
  5. python——运算符

    2024-04-10 11:42:05       32 阅读