Why am I not getting a segmentation fault or at least weird results with this array out of bounds? I'm a bit disappointed. One of the few times I actually want it to happen it won't happen.

int i = 0;
int j = 0; 
int n = 0; 
int a[50];
int frame_page[6];
int no = 0;
int k = 0;
int page_avl = 0;
int cont = 0;
printf("\n enter number\n");
scanf("%d",&n);
printf("\n enter number1 :\n");

for(i=1;i<=n;i++)
scanf("%d",&a[i]);

printf("\n enter number2 :");
scanf("%d",&no);

for(i=0;i<no;i++)
frame_page[i]= -1;

Undefined behavior is unpredictable by definition. You could certainly figure out why it "works", but it would be specific to that version of that compiler.

You can expect to get a segFault when you try to read or write to memory that the operating system thinks does not belong to that program.

So if you have an area of memory allocated to your program, and your array is somewhere inside that area of memory, what will happen when you try to read the byte next to your array (as if you were reading one element too far in the array)? You will be reading memory that still belongs to your program, so the operating system won't mind and will not segFault.

In this case, with your variables as follows:

int i = 0;
int j = 0; 
int n = 0; 
int a[50];
int frame_page[6];
int no = 0;
int k = 0;
int page_avl = 0;
int cont = 0;

while it is up to the compiler etc how they arrange things in memory, there's a good chance that the memory right next to your arrays is occupied by some of those int values that are also part of your program, so when you stray outside your array boundary, you're still reading memory that belongs to your program. Even if you go as far as memory beyond all your variables, maybe your program was allocated a big chunk of memory by the operating system and you're reading memory that you never put anything in, but still belongs to your program.

The operating system will only stop you (with a segFault) when you start trying to use memory it did not give to your program. If you try to read far enough off the end of your array, you will eventually get a segFault.

In summary, you get a segFault when you try to read/write memory that the operating system thinks does not belong to you; NOT for reading some memory that isn't part of an array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.