为什么某些语言未实现边界检查? [英] Why is bounds checking not implemented in some of the languages?

查看:85
本文介绍了为什么某些语言未实现边界检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Wikipedia(http://en.wikipedia.org/wiki/Buffer_overflow)

According to the Wikipedia (http://en.wikipedia.org/wiki/Buffer_overflow)


通常与缓冲区关联的编程语言溢出包括C和C ++,它们没有提供针对访问或覆盖内存任何部分中的数据的内置保护,并且不会自动检查写入数组(内置缓冲区类型)的数据是否在该数组的边界内。边界检查可以防止缓冲区溢出。

Programming languages commonly associated with buffer overflows include C and C++, which provide no built-in protection against accessing or overwriting data in any part of memory and do not automatically check that data written to an array (the built-in buffer type) is within the boundaries of that array. Bounds checking can prevent buffer overflows.

那么,为什么在某些语言(例如C和C ++)中未实现边界检查?

So, why are 'Bounds Checking' not implemented in some of the languages like C and C++?

推荐答案

基本上,这是因为这意味着每次更改索引时,都必须执行if语句。

Basically, it's because it means every time you change an index, you have to do an if statement.

让我们考虑一个简单的C for循环:

Let's consider a simple C for loop:

int ary[X] = {...};  // Purposefully leaving size and initializer unknown

for(int ix=0; ix< 23; ix++){
    printf("ary[%d]=%d\n", ix, ary[ix]);
}

如果我们进行边界检查,则生成的代码ary [ix] 必须类似于

if we have bounds checking, the generated code for ary[ix] has to be something like

LOOP:
    INC IX          ; add `1 to ix
    CMP IX, 23      ; while test
    CMP IX, X       ; compare IX and X
    JGE ERROR       ; if IX >= X jump to ERROR
    LD  R1, IX      ; put the value of IX into register 1
    LD  R2, ARY+IX  ; put the array value in R2
    LA  R3, Str42   ; STR42 is the format string
    JSR PRINTF      ; now we call the printf routine
    J   LOOP        ; go back to the top of the loop

;;; somewhere else in the code
ERROR:
    HCF             ; halt and catch fire

如果我们没有边界检查,那么我们可以写: / p>

If we don't have that bounds check, then we can write instead:

    LD R1, IX
LOOP:
    CMP IX, 23
    JGE END
    LD R2, ARY+R1
    JSR PRINTF
    INC R1
    J   LOOP

这在循环中保存了3-4条指令,这(尤其是在过去)意味着很多。

This saves 3-4 instructions in the loop, which (especially in the old days) meant a lot.

实际上,在PDP-11机器中,甚至更好,因为有一种叫做自动增量寻址的东西。在PDP上,所有寄存器内容等都变成类似

In fact, in the PDP-11 machines, it was even better, because there was something called "auto-increment addressing". On a PDP, all of the register stuff etc turned into something like

CZ  -(IX), END    ; compare IX to zero, then decrement; jump to END if zero

(而且碰巧记得PDP的人比我还记得,不会给我麻烦,因为它的确切语法等等;你是像我这样的老屁,你知道这些东西是如何溜走的。)

(And anyone who happens to remember the PDP better than I do, don't give me trouble about the precise syntax etc; you're an old fart like me, you know how these things slip away.)

这篇关于为什么某些语言未实现边界检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆