Debug Error When Deleting Dynamic Array

I get this error when I'm attempting to delete an array. I'm new to dynamic arrays, and from what I have learned, arrays must be deleted after use. I plan on using this in a function later on, so deleting the array is a must.

Here's the error message:
Debug Error!

HEAP CORRUPTION DETECTED: after Normal block (#154) at 0x007E55A0.
CRT detected that the application wrote to memory after the end of heap buffer.

I know it must be something stupid that I did, but I have very limited knowledge on dynamic arrays.

Here's my code:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
int main()
{	
	//Declare variables
	char persist = ' ';
	int* primes = NULL;
	int size2 = 0;

	//Declare array
	primes = new int[size2];
	//Initialize it
	for (int init = 0; init <= size2; init++)
		primes[init] = 0;
	//End for loop

	for (int size = 0; persist != 'N'; size++)
	{
		cout << "Enter a number for spot " << size + 1 << "(0 to stop):  ";
		cin >> primes[size];

		if (primes[size] != 0)
		{
			persist = 'Y';
			size2++;
		}
		else
		{
			persist = 'N';
			size2;
		}
		//End if
	}

	//Output
	for (int num = 0; num <= size2; num++)
	{
		if (primes[num] != 0)
		cout << "The number in spot " << num + 1 << " is:  " << primes[num] << endl;
		//End if
	}//End for loop

	delete[] primes;
	primes = NULL;
	system("pause");
	return 0;
}


Thanks!
The line:
primes = new int[size2];

creates a new array of size2, which is zero, so you are making an array of no size, and then trying to access it.
I fixed size2 to be initialized to one, but it still is giving me the error. Do I need to change the other similar variables to one as well? Like size, init, and num?
Last edited on
Increasing size2 in your loop is not going to increase the amount of memory you allocated, so you trample all over memory you don't own, corrupting the heap. If you allocate room for 1 int in the array, you may store 1 int and no more.

Topic archived. No new replies allowed.