What happens when you write to memory out of bounds of an array?

前端 未结 1 906
南旧
南旧 2021-01-16 16:15

On a recent test question I was asked to print the output of the following program. I got the answer correct however this program caused me significant mental anguish as I

1条回答
  •  被撕碎了的回忆
    2021-01-16 16:41

    Expanding on Patashu's comment, segmentation faults occur when you access memory from a page in a way which clashes with the page of memory's permissions. In other words, they occur when you access a page of memory in a way that you're not allowed to. What's possibly occurring in your situation is that you are accessing memory still within the same page on which arg_history is stored, for which you obviously have permission to read and write.

    Another possible scenario is that the page of memory right after the one you're working on has the same permissions which allow you to access it the same way.

    In any case, this is undefined behavior in C. Although you witness "expected results," that should not indicate to you that the program is correct. In fact, this is a circumstance in which an out-of-bounds error could potentially go unnoticed, if it doesn't cause a segmentation fault.

    0 讨论(0)
提交回复
热议问题