c - 为什么现代编译器不捕获对数组进行越界访问的尝试?

标签 c arrays compiler-construction

如果 int arr[5] 已初始化,但存储的元素超过 5 个,则多余的元素将在单独的空间中分配内存。 像turbo这样的旧编译器会报告崩溃,因为某些内容被覆盖了 但现代编译器不会发生这种情况,那么他们如何处理这个问题呢?

最佳答案

好吧,我重新开始,所以我想我应该写一些答案:

在一些非常常见的情况下,编译器(或在编译时不可能)不可能检查越界访问。例如,如果数组索引表达式是从输入文件中读取的,或者是使用仅在执行期间建立的值进行计算的结果,则越界访问会在编译器完成其工作后很久发生。

对于运行时系统来说,检查越界访问是很麻烦的。也就是说,每次这样的检查都需要计算要访问的索引,然后检查该索引是否在范围内;所有这些都在“正常”操作之上。

要查看此影响,请使用一个数组操作密集型程序,并在不进行运行时边界检查和运行时边界检查的情况下对其进行编译,并比较执行速度。

似乎广泛使用的编译语言(例如 C、C++、Fortran)都决定默认不生成数组边界检查。但他们的编译器提供了通过数组边界检查生成代码的选项。

(Historical diversion: I have a sneaking suspicion that in the early days C would have struggled to implement array-bounds-checking at run-time since it barely distinguished between arrays and pointers and I'm not sure it always knew what the array bounds were when the code executed. Fortran, on the other hand, uses a dope vector, which includes the size of the array. Perhaps someone more knowledgable than I could correct me on this.)

至于为什么一种语言默认在运行时不检查数组边界,而另一种语言默认检查数组边界,这是语言设计者的问题。

(Hysterical diversion: I think there were probably two reasons for not checking array bounds by default; one, the performance reason; two, these languages were hewn from stone by programmers who were real men who didn't need no stinking help from a machine to write code.)

您可以选择是否使用这种语言。

关于c - 为什么现代编译器不捕获对数组进行越界访问的尝试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61285343/

相关文章:

java - 一次从数组中拉出 10 个项目的最佳方法

c - 关于c语言编程中的指针

c - 功能 "pwr()"无法正常工作

c - 从 C 中的函数传递和返回 2 个数组

c++ - 使用传入参数在 C++ 中创建 3D 数组

objective-c - 警告 "Use of GNU statement expression extension"

c# - c# 编译器是否优化 Count 属性?

c - Telnet 处理 wc 和任何从键盘读取输入的命令

C 指针数组的比较

ios - iOS下使用Stitcher时OpenCV编译报错