Why doesn't my program crash when I write past the end of an array?

前端 未结 9 1179
-上瘾入骨i
-上瘾入骨i 2020-11-22 12:47

Why does the code below work without any crash @ runtime ?

And also the size is completely dependent on machine/platform/compiler!!. I can even give upto 200 in a 64

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 13:01

    Since you're writing outside the boundaries of your array, the behaviour of your code in undefined.

    It is the nature of undefined behaviour that anything can happen, including lack of segfaults (the compiler is under no obligation to perform bounds checking).

    You're writing to memory you haven't allocated but that happens to be there and that -- probably -- is not being used for anything else. Your code might behave differently if you make changes to seemingly unrelated parts of the code, to your OS, compiler, optimization flags etc.

    In other words, once you're in that territory, all bets are off.

提交回复
热议问题