OK, I've been working on a small game project and I got stuck when trying to
add a 'high score' feature. What I intent to do is store the highest score
registered so far and update it if the player scored higher.
This is how I'm pretending to do it:
// blablablabla
// beggining the game and loading everything
std::ifstream file;
file.open("rsc\\hi-score.bin", std::ios::binary);
if (file.is_open())
{
char *temp = nullptr;
file.seekg(0, std::ios::end);
int size = file.tellg();
file.seekg(0, std::ios::beg);
file.read(temp, size);
hiscore = int(*temp);
}
else
hiscore = 1;
file.close();
// blablablabla
// the game ended
if (score > hiscore)
{
std::ofstream file("rsc\\hi-score.bin", std::ios::binary);
if (file.is_open())
file.write((char*)score, sizeof(score));
else
std::cout << "i hate u" << std::endl;
file.close();
}
However, when I run the program, everything seems fine, the file even creates
successfully at the requested directory. But when it reaches the end of the
game and gets to the "file.write()" part, it crashes with the following output:
Unhandled exception at 0x593F6D46 (msvcp110d.dll) in Super Kanji Challange.exe: 0xC0000005:
Access violation reading location 0x00000008.
this attempts to cast the value of score directly as an address, it should use the & operator to get the address of score:
file.write((char*) &score, sizeof(score));
The input code uses a null pointer as the address where the data is to be read into.
It could be fixed by allocating an array of characters of the correct size. but the code looks more complex than necessary.