Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

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

I'm trying to get a segmentation fault by overwriting the stack but the program seems to always hung no matter what.the code is :

#include <stdio.h>

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

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

the program is build as:

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

I'm tying to get a core dump but can't see why the program just hung up without causing segmentation fault. running in gdb also seems to cause the program to hung so i have to terminate it.

Program received signal SIGINT, Interrupt.
0x00005555555551ca in main () at my_make.c:10
10          for (c = 0; c < 20; c++)
question from:https://stackoverflow.com/questions/65623347/why-overflowing-stack-seems-to-cause-program-to-hung-and-not-segmentation-fault

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're [probably] compiling without optimization.

When you loop past the end of array, you are writing into the location where c is stored.

So, you're resetting the value of c to 5.

So, the UB (undefined behavior) produces an infinite loop and not a segfault.

To cause a segfault, replace:

array[c] = 5;

With (e.g.):

array[c] = 150000;

Also, if that's not enough, increase the number of iterations. Replace the for loop with (e.g):

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

Here's the complete code that gets a segfault on my system:

#include <stdio.h>

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

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

    printf("Done
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...