"Delete[]" creates an infinite loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main()
{
	int * major = new int[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
Last edited on
You have several places with undefined behavior:

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.
Last edited on
Topic archived. No new replies allowed.