Reputation: 47
Why does the following code not give a segmentation fault
#include <stdio.h>
int main(){
int i = 0;
int x [10];
while(i < 500){
x[500] = 3;
printf("%d", x[500]);
i++;
}
}
But this code does.
#include <stdio.h>
int main(){
int i = 0;
int x [10];
while(i < 500){
x[i] = 3;
printf("%d", x[i]);
i++;
}
}
I decided to do a little bit of experimentation to see system calls with strace and wanted to see how to OS would handle a segmentation fault. I wrote the first piece of code expecting a segmentation fault but did not get one and was confused since I'm writing to memory not owned by me. So I remember getting faults using a loop and got the second piece of code which gave me a segmentation fault. Now I do not understand why using i
to index the array compared to using an index out of the arrays bound would change if I get a segmentation fault or not.
Upvotes: 0
Views: 250
Reputation: 2978
You're going out-of-bounds in both examples, which is undefined behaviour. Anything can happen now, and there's no guarantee that one instance of UB will do the same thing as another instance.
Upvotes: 2