PhilMAN
PhilMAN

Reputation: 51

C++ stack overflow

Here is some code:

void main()
{
    GameEngine ge("phil", "anotherguy");
    string response;
    do {
        ge.playGame();
        cout << endl << "Do you want to (r)eplay the same battle, (s)tart a new battle, or (q)uit? ";
        cin >> response;
    } while(response == "r" || response == "R" || response == "s" || response == "S" );
}

GameEngine::GameEngine(string name1, string name2)
{
    p1Name = name1;
    p2Name = name2;
}

void GameEngine::playGame()
{
    cout << "PLAY GAME" << endl;
    Army p1, p2;
    Battlefield testField;
    RuleSet rs;

    int xSize = 13; // Number of rows
    int ySize = 13; // Number of columns

    loadData(p1, p2, testField, rs, xSize, ySize);

    ...
}

void GameEngine::loadData(Army& p1, Army& p2, Battlefield& testField, RuleSet& rs, int& xSize, int& ySize)
{
    string terrain = BattlefieldUtils::pickTerrain();
    string armySplit[14];//id index 1
    string ruleSplit[19];//in index 7
    string armyP1, armyP2, ruleSet;
    Skill p1Skills[8];
    Skill p2Skills[8];
    CreatureStack p1Stacks[20];
    CreatureStack p2Stacks[20];

    ...
}

CreatureStack(){quantity = 0; isLive = false; id = -1;};

Army(){};

Battlefield(){};

RuleSet(){};

I have posted every line of code that executes until the program crashes. This code ran fine for a long time, I added some stuff that does not even execute until way after the code I have posted here, and bam, a stack overflow that occurs at GameEngine::loadData() line: CreatureStack p2Stacks[20]; will not go away. What am I doing wrong here? Is that all the stack can handle? I increased the stack size in Visual Studio and got the error to go away, but that slowed things down considerably, so how do I get to the source of the issue and fix that?

Upvotes: 5

Views: 629

Answers (1)

abelenky
abelenky

Reputation: 64720

Clearly, CreatureStack is a large object. You are allocating 20 of them on the stack. Result: stack overflow.

Instead, change to new or malloc for your array of CreatureStack's, moving them into heap memory instead of stack.

Don't forget to free them when done.

Upvotes: 4

Related Questions