Error with HEAP corruption

I'm writing a simple shooting game to brush up on my c++, and I am running into an error I don't know how to fix, or even what is wrong.

Here's the error: imgur.com/Z1ukmTh.png
The error happens when I delete[] gameObjArray the second time this function is called.
At line 10.

Here's my code for the function involved.
What's this function does is: if there is less than 10 enemies, every 2 seconds it will spawn one. I have it create a new array of enemies every time it spawns one, so that I don't have to set a max amount of enemies.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void gameEngine::spawnEnemies()
{
	if (enemyCount < 10 && (time(NULL) - prevTime) > 2) {
		tempGameObjArray = new gameObject[enemyCount];
		for (int x = 0; x < enemyCount; x++) {
			tempGameObjArray[x] = gameObjArray[x];
		}
		enemyCount++;		
		delete[] gameObjArray;
		gameObjArray = new gameObject[enemyCount];
		for (int x = 0; x < (enemyCount - 1); x++) {
			gameObjArray[x] = tempGameObjArray[x];
		}
		delete[] tempGameObjArray;
		gameObjArray[enemyCount].enemy(&spriteArrObj);
	}
}
Last edited on
The error says you're accessing memory that isn't yours.

gameObjArray[enemyCount] does not exist. The last element in the array is gameObjArray[enemyCount-1] . On line 15, you're accessing memory that isn't yours.


While I'm here, don't use new. Don't use delete. Don't use arrays. These are for advanced users.

Use vectors. This situation here, where you're manually copying arrays around because you need to increase the size of it, is screaming out for a vector. You're making this much harder for yourself.
Last edited on
The last element of the Array is gameObjArray[enemyCount] which should be three by the time it throws that error.

I used enemyCount - 1 in the for loop so that I didn't copy from an element in tempGameObjArray that wasn't there.

gameObjArray[enemyCount].enemy(&spriteArrObj); on line 15 should be there. It's just not copied from anything.

When I do gameObjArray = new gameObject[enemyCount]; it should initialize gameObjArray[enemyCount].enemy(&spriteArrObj);
Last edited on
On line 10, you an making an array of size enemyCount.
gameObjArray = new gameObject[enemyCount];

enemyCount has the same value on line 10 and line 15.

On line 15, you're trying to access an element in that array that does not exist. The last element is at index enemyCount-1.

If enemyCount is 3, then the following elements exist:
1
2
3
gameObjArray[0]
gameObjArray[1]
gameObjArray[2]


gameObjArray[3] does not exist. gameObjArray[enemyCount] does not exist. On line 15, you're trying to use something that doesn't exist. Don't do that.
Last edited on
Topic archived. No new replies allowed.