views:

188

answers:

1
+3  Q: 

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 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 I would rather just get to the source of the issue and fix that.

+4  A: 

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.

abelenky
I'd suggest storing your `CreatureStack`s in a smart pointer, such as `boost::shared_ptr`so that you don't have to remember to delete them. http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/shared_ptr.htm
Josh Townzen
Or a std::vector of CreatureStacks might be easier since it'll free itself :)
Peter