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

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

    Most implementations don't check for these kinds of errors. Memory access granularity is often very large (4 KiB boundaries), and the cost of finer-grained access control means that it is not enabled by default. There are two common ways for errors to cause crashes on modern OSs: either you read or write data from an unmapped page (instant segfault), or you overwrite data that leads to a crash somewhere else. If you're unlucky, then a buffer overrun won't crash (that's right, unlucky) and you won't be able to diagnose it easily.

    You can turn instrumentation on, however. When using GCC, compile with Mudflap enabled.

    $ gcc -fmudflap -Wall -Wextra test999.c -lmudflap
    test999.c: In function ‘main’:
    test999.c:3:9: warning: variable ‘arr’ set but not used [-Wunused-but-set-variable]
    test999.c:5:1: warning: control reaches end of non-void function [-Wreturn-type]
    

    Here's what happens when you run it:

    $ ./a.out 
    *******
    mudflap violation 1 (check/write): time=1362621592.763935 ptr=0x91f910 size=151
    pc=0x7f43f08ae6a1 location=`test999.c:4:13 (main)'
          /usr/lib/x86_64-linux-gnu/libmudflap.so.0(__mf_check+0x41) [0x7f43f08ae6a1]
          ./a.out(main+0xa6) [0x400a82]
          /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xfd) [0x7f43f0538ead]
    Nearby object 1: checked region begins 0B into and ends 141B after
    mudflap object 0x91f960: name=`alloca region'
    bounds=[0x91f910,0x91f919] size=10 area=heap check=0r/3w liveness=3
    alloc time=1362621592.763807 pc=0x7f43f08adda1
          /usr/lib/x86_64-linux-gnu/libmudflap.so.0(__mf_register+0x41) [0x7f43f08adda1]
          /usr/lib/x86_64-linux-gnu/libmudflap.so.0(__mf_wrap_alloca_indirect+0x1a4) [0x7f43f08afa54]
          ./a.out(main+0x45) [0x400a21]
          /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xfd) [0x7f43f0538ead]
    number of nearby objects: 1
    

    Oh look, it crashed.

    Note that Mudflap is not perfect, it won't catch all of your errors.

提交回复
热议问题