【C语言】数组越界

目录

  • [1. 越界](#1. 越界)
    • [1.1 静态数组越界](#1.1 静态数组越界)
    • [1.2 动态数组越界](#1.2 动态数组越界)

1. 越界

1.1 静态数组越界

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

c 复制代码
#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' */

输出:

bash 复制代码
[0] = 0
[1] = 0
[2] = 0
[3] = 0
[4] = 0
[5] = 32766	#error overflow

有上面的输出就说明它并不会造成编译错误! 因为C语言的编译器并不会判断你的代码访问越界 了。错误就这样通过编译 了。

数组访问出现越界,结果是不可预测(可能导致程序崩溃、安全漏洞或其他不可预测的行为)。有时什么事也没有,程序一直运行(某些错误可能已经存在);有时则是程序崩溃。因此,在使用数组 时一定要判断是否越界以保证程序的正确性。

1.2 动态数组越界

c 复制代码
#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 */

编译后输出:

bash 复制代码
[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。存在逻辑错误却可以编译执行,还不会报错。 其是错误已经发生了。

相关推荐
祈安_2 天前
C语言内存函数
c语言·后端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish4 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人4 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J4 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹44 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow4 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法
Sunsets_Red4 天前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛