0

For a project of mine, I am writing a save file reader. In the latest build I am getting a runtime error Unhandled exception at 0x00075256 in Final Assessment.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.

How can I go on to identify and correct the source of this error?

I believe the error happens when I create the ifstream object saveFile(), but I have been unable to find the exact source.

bool Game::load(){
    string data[9];
    ifstream saveFile("save.dat");
    int x = 0;
    if (saveFile.is_open()){
        while (!saveFile.eof()){
            getline(saveFile,data[x]);
            x++;
        }
        saveFile.close();

        string savePlayerName = data[0];
        int saveBaseHealth = stringToInt(data[1]);
        int saveHealth = stringToInt(data[2]);
        int saveKilled = stringToInt(data[3]);
        int saveMoney = stringToInt(data[4]);

        string saveWeaponName = data[5];;
        int saveAttack = stringToInt(data[6]);

        string saveArmorName = data[7];
        int saveDefense = stringToInt(data[8]);

        mainPlayer.setName(savePlayerName);
        mainPlayer.setBaseHealth(saveBaseHealth);
        mainPlayer.setHealth(saveHealth);
        mainPlayer.setEnemiesKilled(saveKilled);
        mainPlayer.setMoney(saveMoney);

        mainWeapon.setName(saveWeaponName);
        mainWeapon.setAttackPower(saveAttack);

        mainArmor.setName(saveArmorName);
        mainArmor.setDefense(saveDefense);
        return true;
    }
    else
    {
        return false;
    }
}

Debug

Francesco
  • 2,982
  • 1
  • 29
  • 44
clifford.duke
  • 3,640
  • 9
  • 33
  • 62

1 Answers1

8

Maybe not the immediate reason of your crash, but here goes:

while (!saveFile.eof()) is an anti-pattern that's a common source of off-by-one errors. The reason is that it returns true only after an attempt is made to read past the end of file. That means you get one iteration too much, one x++ too much and you go out of bounds in data[x], invoking undefined behaviour.

Sometimes. Unfortunately, you might get away with it and it would appear to work.

Change the loop to

while (getline(saveFile, tempString) && x < 9) {
    data[x] = temp;
    ++x;
}

and see if it makes a difference.

(The above code doesn't account for input with less than 9 lines, mind you. Also, I'd suggest you use a std::vector instead of a C-array.)

jrok
  • 51,107
  • 8
  • 99
  • 136