为什么堆栈溢出似乎导致程序挂起而不是段错误?

Why overflowing stack seems to cause program to hung and not segmentation fault?

我试图通过覆盖堆栈来获得分段错误,但程序似乎总是挂起,无论 what.the 代码是:

#include <stdio.h>

int main(){
    printf("start\n");
    printf("Ending\n");
    int array[5] = {1, 2, 3, 4, 5};
    int c;

    for (c = 0; c < 20; c++)
        array[c] = 5;
    printf("Done");
}

程序构建为:

    gcc -march=x86-64 -fno-stack-protector -gdwarf -o my_make my_make.c

我想获取核心转储,但不明白为什么程序只是挂了而没有导致分段错误。 运行 在 gdb 中似乎也导致程序挂起,所以我必须终止它。

Program received signal SIGINT, Interrupt.
0x00005555555551ca in main () at my_make.c:10
10          for (c = 0; c < 20; c++)

你[可能]编译没有优化。

当您循环经过 array 的末尾时,您正在写入存储 c 的位置。

因此,您正在将 c 的值重置为 5

所以,UB(未定义的行为)产生了一个无限循环并且不是一个段错误。

导致段错误,替换:

array[c] = 5;

与(例如):

array[c] = 150000;

此外,如果这还不够,请增加迭代次数。将 for 循环替换为(例如):

for (c = 0; c < 20000; c++)

这是在我的系统上出现段错误的完整代码:

#include <stdio.h>

int
main()
{
    printf("start\n");
    printf("Ending\n");
    int array[5] = { 1, 2, 3, 4, 5 };
    int c;

    for (c = 0; c < 10000000; c++)
        array[c] = 15000;

    printf("Done\n");
}