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);
}
}
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.