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

前端 未结 6 670
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  难免孤独
    2020-12-07 02:14

    Undefined behavior.

    That's what it is. You can try to write out of bounds but it's not guaranteed to work. It might work, it might not. What happens is completely undefined.

    Why is this allowed to happen?

    Because the C and C++ standards allow it. The languages are designed to be fast. Having to check for out of bounds accesses would require a run-time operation, which would slow the program down.

    why is that address at p[500] even writable?

    It just happened to be. Undefined behavior.

    I see that when I try to edit at a larger value...

    See? Again, it just happened to segfault.

    When malloc is called, perhaps the OS decides to give the process an entire page.

    Maybe, but the C and C++ standards don't require such behavior. They only require that the OS make at least the requested amount of memory available for use by the program. (If there's memory available.)

提交回复
热议问题