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:
// beggining the game and loading everything
char *temp = nullptr;
int size = file.tellg();
hiscore = int(*temp);
hiscore = 1;
// the game ended
if (score > hiscore)
std::ofstream file("rsc\\hi-score.bin", std::ios::binary);
std::cout << "i hate u" << std::endl;
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.