C++堆栈溢出

Phi*_*MAN 5 c++ stack-overflow

这是一些代码:

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(){};
Run Code Online (Sandbox Code Playgroud)

我已发布执行的每一行代码,直到程序崩溃.这段代码很好地运行了很长时间,我添加了一些甚至在我发布的代码之后都没有执行的东西,而bam,GameEngine::loadData()在行发生的堆栈溢出:CreatureStack p2Stacks[20];不会消失.我在这做错了什么?所有堆栈都可以处理吗?我增加了Visual Studio中的堆栈大小并且错误消失了,但这大大减慢了速度,所以我如何找到问题的根源并修复它?

abe*_*nky 4

显然,CreatureStack 是一个大对象。您将在堆栈上分配其中的 20 个。结果:堆栈溢出。

相反,更改为CreatureStack 数组newmalloc将其移至 CreatureStack 数组,将它们移至堆内存而不是堆栈中。

完成后不要忘记释放它们。

  • 或者 CreatureStacks 的 std::vector 可能会更容易,因为它会释放自己:) (6认同)