Why is it that we can write outside of bounds in C?

前端 未结 6 668
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 01:37

I recently finished reading about virtual memory and I have a question about how malloc works within the Virtual address space and Physical Memory.

For example (cod

6条回答
  •  旧时难觅i
    2020-12-07 02:27

    It's simply that in C the concept of an array is rather basic.

    The assignment to p[] is in C the same as:

    *(p+500)=999999;
    

    and all the compiler does to implement that is:

    fetch p;
    calculate offset : multiply '500' by the sizeof(*p) -- e.g. 4 for int;
    add p and the offset to get the memory address
    write to that address.
    

    In many architectures this is implementable in one or two instructions.

    Note that not only does the compiler not know that the value 500 is not within the array, it doesn't actually know the array size to begin with!

    In C99 and later, some work has been done to make arrays safer, but fundamentally C is a language designed to be fast to compile and fast to run, not safe.

    Put another way. In Pascal, the compiler will prevent you from shooting your foot. In C++ the compiler provides ways to make it more difficult to shoot your foot, while in C the compiler doesn't even know you have a foot.

提交回复
热议问题