How can an operating system detect an out of range segmentation fault in C?

I encounter this problem when learning Operating System and I’m really interested in how operating system detecs whether an array index is out of range and therefore produce a segmentation fault?

int main(){
    char* ptr0;
    ptr0[0] = 1;
}

The code above will absolutely produce a segmentation fault, since ptr0 is not allocated with any memory.

But if add one line, things change.

int main(){
    char* ptr0;
    char* ptr1 = ptr0;
    ptr0[0] = 1;
}

This code won’t cause any fault, even you change ptr0[0] to ptr0[1000], it still won’t cause any segmentation fault.

I don’t know why the line has such power

char* ptr1 = ptr0

I tried to disassmbly these codes but find little information.

Could somebody explain that to me on the perspective of memory allocation? thanks a lot.

Answer

A segmentation fault happens when a process attempts to access memory it’s not supposed to, not necessarily if an array is read out of bounds.

In your particular case the variable ptr0 is uninitialized, and so if you attempt to read it any value may be read and it need not even be consistent. So in the case of the first program the value that was read happened to be an invalid memory address and attempting to read from that address triggered a sigfault, while in the case of the second program the value read happened to be a valid address for the program and so a segfault was not generated.

When I ran these programs, both resulted in a segfault. This demonstrates the undefined behavior present in the program which attempts to dereference an invalid pointer.

When a program has undefined behavior, the C standard makes no guarantees regarding what the program will do. It may crash, it may output unexpected results, or it may appear to work properly.