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\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");
}
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++)
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\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");
}