C program: Why am I not getting Segmentation Fault? Is it UB?

I am reading the book: Computer Systems, A Programmer's Perspective.

I wrote the following code just for my own understanding:
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main()
{
    int A[10];
    int i;
    for (i = 0; i < 14; i++)
        A[i] = i;
    printf("%d\n",A[11]);
    return 0;
}


This code does not give segmentation fault. However if I extend the termination condition of the for loop to "< 15", then it results in seg fault.

Is it UB that I am experiencing or is there a valid reason for such behaviour?

Does it have anything to do with an int taking 4 bytes of memory space vis-a-vis a pointer taking 8 bytes on a 64 bit machine?

Thanks!
Last edited on
Your 'A' array is 10 units large and you are writing to the 15th element. By all rights this should seg fault to, it's just a matter of chance that it does not. Moving this to the beginners section will provide more help if you need it.
Is it UB that I am experiencing or is there a valid reason for such behaviour?


It is undefined behavior that you are experiencing and there is a valid reason for such behavior. The valid reason is that it is undefined behavior and undefined behavior is.. well, undefined. It could do anything and have conforming behavior.
ok, thanks for the responses!
Topic archived. No new replies allowed.