Why does the following code compile and run.
I have created an integer array and assigned its size to 10, why then does the program not return an error that I am trying to access an element outside the array, when inside the for loop?
In addition, I would like to understand the concept of new, is my usage correct(I have not assigned how much memory *arrays needs), it is my understanding that new allows me to create an array of dynamic size (meaning that I can increase the size of this array indefinitely during runtime, correct me if I am wrong). If this is correct what is the difference in me using new or simply just allocating array[]; since both apparently allow me to increase the size of my array at runtime as can be seen with this example. I know about scope, stack and heap differences, so assume that both variables are only declared in main and use the following code as the example.
#include <iostream>
using namespace std;
int main()
{
int array[10];
int *arrays;
arrays = new int();
for (int i=0; i<450; i++)
{
arrays[i] = i;
cout << arrays[i] << " ";
array[i] = i;
cout << array[i] << endl;
}
return 0;
}
Accessing elements beyond the bounds of an array results in Undefined Behavior.
Compilers do not need to do anything specific in such guaranteed Undefine Behavior cases.
And potentially anything might happen, your program might crash or not or show erratic behavior and this is allowed by the Standard.
Reference :
C++ Standard section 1.3.24 states:
Your understanding of
newis not correct.newallows you to allocate a fixed amount of memory on the freestore (a.k.a heap). It does not allocate additional memory if you extend the bounds of the allocated memory. It is up to you to ensure that you have to allocate enough memory so that you do not exceed the bounds.In your program you are trying to allocate memory equal to 10 array elements so you should be doing:
Also, do not forget to call
delete[]once you are done using the allocated memory or it results in a memory leak.If you need a data structure which increases automatically as per your usage, C++ provides that in the form of std::vector.