0

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.

J...S
  • 5,079
  • 1
  • 20
  • 35
Shawnzye
  • 47
  • 1
  • 6
  • 1
    it's undefined behaviour. – Jean-François Fabre Oct 08 '17 at 19:12
  • you're destroying the return address for sure in the second example, in the first example you're writing somewhere but it doesn't have any negative effect. Undefined behaviour. – Jean-François Fabre Oct 08 '17 at 19:14
  • I have never heard of undefined behavior so I looked it up and read a little bit about it. Correct me if I'm wrong but in the first example the compiler knows what will happen when I write to 500 so it doesn't through an error. While in the second example the compiler can not know forsure what will happen if I have a variable in a loop accessing memory so it throws an error? – Shawnzye Oct 08 '17 at 19:24
  • the compiler has nothing to do with it. In the second example you're violating 1 memory address, in the second example you're violating 490 memory addresses, so 490 times more chances to get a crash – Jean-François Fabre Oct 08 '17 at 19:25
  • 1
    Possible duplicate of [How dangerous is it to access an array out of bounds?](https://stackoverflow.com/questions/15646973/how-dangerous-is-it-to-access-an-array-out-of-bounds) – Bo Persson Oct 08 '17 at 19:27
  • Okay thank you. In such that is why Java is considered a "safe language" since access out memory is not allowed? – Shawnzye Oct 08 '17 at 19:29
  • yeah, because there are no pointers, only arrays, so boundary checks. – Jean-François Fabre Oct 08 '17 at 19:30

1 Answers1

2

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.

frslm
  • 2,969
  • 3
  • 13
  • 26