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

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

    Under the C spec, accessing an element past the end of an array is undefined behaviour. Undefined behaviour means that the specification does not say what would happen -- therefore, anything could happen, in theory. The program might crash, or it might not, or it might crash hours later in a completely unrelated function, or it might wipe your harddrive (if you got unlucky and poked just the right bits into the right place).

    Undefined behaviour is not easily predictable, and it should absolutely never be relied upon. Just because something appears to work does not make it right, if it invokes undefined behaviour.

提交回复
热议问题