Array overflow (why does this work?)

最后都变了- 提交于 2019-11-27 22:37:26

It's undefined behavior. UB comes in many flavors. Here are a few:

1) It will kick your dog.

2) It will reformat your hard drive.

3) It will work without a problem.

In your case, with your compiler and on your platform and on this particular day, you are seeing (3). But try it elsewhere, and you might get (1), (2), or something else completely (most likely an access violation).

C/C++ does not do boundary checking when using arrays.

Since you are declaring a stack based array. Accessing outside the bounds of the array will just access another part of already allocated stack space.

So basically when you access something that is out of bounds, it won't throw a segmentation fault unless its completely out of your stack memory.

C/C++ is dangerous with array boundaries remember that!

The stack is very large. On Windows, it's 1 MB.

Since the program doesn't do much, the array would have been allocated close to the beginning of the stack. This means there would be almost 1 MB of empty space between the end of the array and the end of the stack.

So what does this mean? When you write past the end of the array, you're just clobbering your own stack space, not other programs', so the OS doesn't stop you and the program continues to run.

Here, you know that array index starts from 0 and goto 5

You input your counter as 5 which starts from 1 and goto 5

You are using index 1 for counter 1 ,index 2 for couter 2, and so on .

Index 0 still have no input value and contain garbage value.

Firstly, array sizes need to be constant so

 int arr[size] 

will not work as size is a variable, so, either fix the size of the array at compile time or use dynamic memory allocation.

i.e. either

  const int size =5; 
  int arr[size];

or

  int arr[5];

or

  int* arr = new int[5];

AND..

Taking a pointer to one element beyond the end of array is guaranteed to work in C++. This is important for many algorithms provided by the STL. However, since such a pointer does not infact point to an element of the aray, it may not be used for reading and writing. On the other hand, the result of taking the address of the element before the initial element is undefined and should be avoided..

i.e. you can take the address of that variable and then come back but can't use it!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!