Segfault on stack overflow

前端 未结 6 2163
囚心锁ツ
囚心锁ツ 2021-01-04 08:20

Why does the linux kernel generate a segfault on stack overflow? This can make debugging very awkward when alloca in c or fortran creation of temporary arrays overflows. Sur

6条回答
  •  有刺的猬
    2021-01-04 08:29

    The "kernel" (it's actually not the kernel running your code, it's the CPU) doesn't know how your code is referencing the memory it's not supposed to be touching. It only knows that you tried to do it.

    The code:

    char *x = alloca(100);
    char y = x[150];
    

    can't really be evaluated by the CPU as you trying to access beyond the bounds of x.

    You may hit the exact same address with:

    char y = *((char*)(0xdeadbeef));
    

    BTW, I would discourage the use of alloca since stack tends to be much more limited than heap (use malloc instead).

提交回复
热议问题