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

后端 未结 6 1325
伪装坚强ぢ
伪装坚强ぢ 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:02

    So how is this possible?

    Because the stack was, on your machine, large enough that there happened to be a memory location on the stack at the location to which &arr[150] happened to correspond, and because your small example program exited before anything else referred to that location and perhaps crashed because you'd overwritten it.

    The compiler you're using doesn't check for attempts to go past the end of the array (the C99 spec says that the result of arr[150], in your sample program, would be "undefined", so it could fail to compile it, but most C compilers don't).

提交回复
热议问题