-1

I have declare an int array of just three elements but I notice that I can access to array indexes bigger

int x[3];
int length = sizeof(x)/sizeof(x[0]);
printf("\n the length defined is %i but I can still setting and getting other indexes")
Pedro Machado
  • 158
  • 2
  • 10

2 Answers2

1

One of the things that makes C fast is that it doesn't do any type of bounds checking on arrays. It expects programmers to know what they're doing to stay within the proper bounds.

Failure to do so means accessing a portion of memory outside the bounds of the array and leads to undefined behavior.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

When accessing an index bigger than an array length, what you are actually doing is to "invade" a memory area that you are not supposed to access. This can lead to unexpected behavior of your application or a crash.

  • I understand that but do you know why is that possible? – Pedro Machado May 20 '16 at 00:39
  • The array size declaration is about how much memory will be allocated. However, when accessing that allocated memory, it is up to the developer to control where to read/write in memory areas. The compiler doesn't check whether the developer is accessing a legal memory area. – Rodrigo Nogueira May 20 '16 at 00:47