为什么现代编译器不捕获对数组进行越界访问的尝试?
Why don't modern compilers catch attempts to make out-of-bounds access to arrays?
如果初始化了 int arr[5] 但存储了超过 5 个元素,那么额外的元素将在单独的 space 中分配内存。
像 turbo 这样的旧编译器报告崩溃是因为某些东西被覆盖了
但现代编译器不会发生这种情况,那么他们如何处理这个问题?
嗯,我搬到重新打开所以我想我应该写一些答案:
编译器不可能(或编译时不可能)在一些非常常见的情况下检查越界访问。例如,如果数组索引表达式是从输入文件中读取的,或者是使用仅在执行期间建立的值进行计算的结果,那么越界访问会在编译器完成其工作很久之后发生。
运行时间系统检查越界访问是一个负担。也就是说,每次这样的检查都需要计算要访问的索引,然后检查该索引是否在范围内;所有这些都在 'normal' 操作之上。
要查看此操作的影响,请使用数组操作密集型程序并在不进行 运行 时间边界检查和 运行 时间边界检查的情况下进行编译,并比较执行速度。
似乎广泛使用的编译语言(例如 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.)
您可以选择是否使用这种语言。
如果初始化了 int arr[5] 但存储了超过 5 个元素,那么额外的元素将在单独的 space 中分配内存。 像 turbo 这样的旧编译器报告崩溃是因为某些东西被覆盖了 但现代编译器不会发生这种情况,那么他们如何处理这个问题?
嗯,我搬到重新打开所以我想我应该写一些答案:
编译器不可能(或编译时不可能)在一些非常常见的情况下检查越界访问。例如,如果数组索引表达式是从输入文件中读取的,或者是使用仅在执行期间建立的值进行计算的结果,那么越界访问会在编译器完成其工作很久之后发生。
运行时间系统检查越界访问是一个负担。也就是说,每次这样的检查都需要计算要访问的索引,然后检查该索引是否在范围内;所有这些都在 'normal' 操作之上。
要查看此操作的影响,请使用数组操作密集型程序并在不进行 运行 时间边界检查和 运行 时间边界检查的情况下进行编译,并比较执行速度。
似乎广泛使用的编译语言(例如 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.)
您可以选择是否使用这种语言。