The following program compiles (using MS Visual Studio 2010) with no errors or warnings and runs without any error, why? Thanks in advance for explanation.

#include <stdio.h>

int f[3] = { 1,2,3 };
int g[4] = { 12,45,55,65 };

int main(int argc, char *argv[])
{	
	printf("%d\n", f[5]);
	return 0; 
}

No reply is needed. I have resolved it.

C isn't a protected environment. You can do these things, but you can't rely on the result being predictable or reproducible.

Actually this code should give an error as the array index you are accessing is outofbound

Actually this code should give an error as the array index you are accessing is outofbound

Once again, C isn't a protected environment. You might get a compiler warning, but an error isn't likely. The code may also run without error if you don't walk off of the process' allocated memory or corrupt anything within the process and cause subsequent memory errors. This is an instance of undefined behavior.

Makes sense it might do this, doesn't it?

First, it makes room for f[], then it makes room for g[]. Nothing in between is made, so it's quite probable that f[] is just beneath or above g[].

When you "walk" off the end of f[]'s boundary, what might you very well run into, except g[]?

Wouldn't be anything to rely on since it's totally undefined, but you can see how it might happen, just like that.

Now go program the right way. ;)

THis doesn't turn up showing an error message..
this is because there is no array bound checking in C
AS far as C is concerned its completely the resposibility of the programmer to ensure that the array indices are within array size limits....

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.