Exceeding array bound in C — Why does this NOT crash?

后端 未结 6 1318
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 15:25

I have this piece of code, and it runs perfectly fine, and I don\'t why:

int main(){
   int len = 10;
   char arr[len];
   arr[150] = \'x\';
}
6条回答
  •  情深已故
    2020-11-30 16:18

    C compilers generally do not generate code to check array bounds, for the sake of efficiency. Out-of-bounds array accesses result in "undefined behavior", and one possible outcome is that "it works". It's not guaranteed to cause a crash or other diagnostic, but if you're on an operating system with virtual memory support, and your array index points to a virtual memory location that hasn't yet been mapped to physical memory, your program is more likely to crash.

提交回复
热议问题