int main()
{
int * major = newint[2];
major[0] = 9;
major[1] = 12;
major[2] = 15;
for (int i = 0; i < 3; i++)
{
cout << major[i] << endl;
}
delete[] major;
char wait;
cin >> wait;
cout << major[0];
cout << major[2];
cin >> wait;
return 0;
}
I was experimenting with dynamic memory allocation. Basically, I am really confused with DMA.
I specified that I only have 2 memory addresses, but when I set major[2] = 15, it worked. Why would it work if I stepped outside the bounds of my array.
Then, I try to delete[]. All it did was create an infinite loop.
I'm a bit confused. Any thoughts appreciated.
EDIT: Sorry, I meant to put this on Beginners. Ekkk
1) You are creating array which can hold two values with indices 0 and 1, but assigning it three values.
2) Accessing out of bounds in a loop
3) Accessing memory after it was deallocated.
There is no surprise that your program behaves funny.
In C++ as soon as you do something prohibited by language rules, you lose all rights to complain about strange behavior. C++ is not sandbox language. It assumes that programmer knows what he is doing.