Shawnzye
Shawnzye

Reputation: 47

C segmentation fault using variable to index compared to no fault using number to index array

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

Answers (1)

frslm
frslm

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

Related Questions