Problem with exception/writing violation

Hello, I am currently taking an introductory C++ course in college and am working on the final project but have run into an error.

I am using Windows 7 64-bit and am compiling in VS 2010.

The error occurs in CentOS using Emacs as well. (Which is what I will be graded in.)

It is a Rock, Paper Scissors game where the user can play a game against a second player or the computer. Each game is comprised of 3 rounds. The error occurs when a player wins a match for a second time. It does not occur when the computer wins more than once.

I receive the following error message.

Unhandled exception at 0x58bacac8 (msvcr100d.dll) in project2.exe: 0xC0000005: Access violation writing location 0xcccccccc.



The debug screen shows the error happening in this section.
mov [edi+ecx*4-4],eax ;U - put dword into destination



Now, I am a beginner, so I haven't the faintest idea what that means.


Here is the code in which the error is happening.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
case 2://Play 1-Player Game
			{
			//Highscore profile
			HighScore NewScore;

			//Start Game
			cout << endl
				<< "Game Start!"
				<< endl;

			//Scores
			PlayerScores Game = {0,0};

			

			for(int i = 0; i<3; i++)//Drive game
			{
				gameChoice p1Choice;
				gameChoice p2Choice;
				cout << "Round " << i+1 << endl
					<< endl;

				//Player Choice
				p1Choice=getChoice();

				//Computer Choice
				p2Choice=cpuChoice();

				gameChoice Rock=ROCK;

				//Calculate winner
				CalculateScores(p1Choice, Rock, Game);

				//Display choices
				cout << "You chose " << itemName[p1Choice]
					<< endl << "Your opponent chose " << itemName[p2Choice]
					<< endl;

				if(i!=2)
					cout << "Current score: "
						<< endl << name << ": " << Game.p1Score
						<< endl << "Opponent: " << Game.p2Score
						<< endl << endl;
			}

			//Display result message
			if(Game.p1Score>Game.p2Score)
			{
				cout << "You are the winner!";
				activeScores.p1Score++;
			}

			else if(Game.p1Score==Game.p2Score)
				cout << "It's a tie!";

			else
				cout << "You lost!";

			cout << endl << endl;


			//Display final score
			cout << "Final Score: "
						<< endl << name << ": " << Game.p1Score
						<< endl << "Opponent: " << Game.p2Score
						<< endl << endl;

			//Create Highscore entry
			NewScore.name=name;
			NewScore.score=activeScores.p1Score;

			//Update
			UpdateScores(currentScores,NewScore,3);

			cout << "Press ENTER to continue...";
			cin.ignore(80,'\n');
			cin.get(); //Wait for user to press Enter key to move on
			cin.ignore(80,'\n');
			cout << endl << endl << endl;
			
			//end game
			break;
			}



This is only the code for a single-player game, but the error occurs the same way in the multi-player game, therefore the error should be equally noticeable in this section.


Here are the function definitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
int random(int max)
Calculates a random number from 1 to max

Parameters:
	max, value parameter for highest possible value

Return Type: int for random number from 1 to max
*/

int random(int max)
{
	int r;

	//Feed random number generator 
	srand(time(NULL));
	//generate number from 1 to max
	r = rand() % max + 1;
	cout << r;
	return r;
}


/*
void CalculateScores(gameChoice p1Choice, gameChoice p2Choice,
					 PlayerScores& scores)
Determines winner based on choice of weapon

Parameters:
	p1Choice: Value Parameter for player 1 choice
	p2Choice: Value Parameter for player 2 choice
	scores: Reference Parameter for where score is updated

Return type: void
*/
void CalculateScores(gameChoice p1Choice, gameChoice p2Choice,
					 PlayerScores& scores)
{
	//Table of outcomes
	PlayerScores pscores[3][3]=
	{
		{//P1 picks Rock
			{0,0},{0,1},{1,0}
		},
		{//P1 picks Paper
			{1,0},{0,0},{0,1}
		},
		{//P1 picks Scissors
			{0,1},{1,0},{0,0}
		},
							};

	//find the winner
	scores.p1Score += pscores[p1Choice][p2Choice].p1Score;
	scores.p2Score += pscores[p1Choice][p2Choice].p2Score;
}

/*
void UpdateScores(HighScore Old[], HighScore New, int size)
Insert current score into Highscores if high enough.

Parameters:
	Old: Old Highscores read from text file
	New: New Highscores to compare to old
	size: Number of Highscore entries

Return Type: void
*/
void UpdateScores(HighScore Old[], HighScore New, int size)
{
	//Check scores
	for(int i = 0; i<size; i++)
	{
		if(New.score>Old[i].score)
		{
			for(int ii=size; ii>i; i++)
			{
				Old[ii].score=Old[ii-1].score;
				Old[ii].name=Old[ii-1].name;
			}
			Old[i].score=New.score;
			i=size;
		}
	}

}

/*
ofstream GetHighscores(HighScore Score[], int size)
Read Highscores from file, if file does not exist, create it. 
Return file for later output

Parameters: 
	Score: array of scores to store new scores
	Size: size of array

Return Type: void
*/

void GetHighscores(HighScore Score[], int size)
{
	ofstream outFile;
	ifstream inFile;
	//Read the file
	inFile.open("highscore.txt");

	//Check if file doesn't exist
	if(!inFile)
	{
		inFile.close();
		//Create file
		outFile.open("highscore.txt");
		outFile << "Bob" << endl;
		outFile << 3;
		outFile << "Joe" << endl;
		outFile << 2;
		outFile << "Smith" << endl;
		outFile << 1;
		outFile.close();
		inFile.open("highscore.txt");
	}
	//read contents of file
	for (int i=0;i<size;i++){
		getline(inFile, Score[i].name);

		inFile >> Score[i].score;
	}
	
	//Close infile and open outfile
	inFile.close();
}

/*
gameChoice getChoice()
Prompts user for selection.

Parameters:
	None

Return Type: gameChoice enum type for Players choice
*/
gameChoice getChoice()
{
	gameChoice pChoice;
	int gameMenu=-4;

	//Menu
	while(gameMenu>3 || gameMenu<1)//Prompt user for input
	{
		cout << "1. Rock"
			<< endl << "2. Paper"
			<< endl << "3. Scissors"
			<< endl; //Display menu

		cout << "Enter your choice: ";
		cin >> gameMenu;//User input

		if(gameMenu>3 || gameMenu<1)
		cout << "Error: Invalid input."
			<< endl;
	}

	cout << endl;


	//Set player selection
	if(gameMenu==1)
		pChoice=ROCK;
	if(gameMenu==2)
		pChoice=PAPER;
	if(gameMenu==3)
			pChoice=SCISSORS;

	return pChoice;
}


/*
gameChoice cpuChoice()
Gets cpu selection.

Parameters:
	None.

Return Type: gameChoice enum type
*/

gameChoice cpuChoice()
{
	gameChoice pChoice;
	int gameMenu;

	gameMenu=random(3);

	if(gameMenu==1)
		pChoice=ROCK;
	if(gameMenu==2)
		pChoice=PAPER;
	if(gameMenu==3)
		pChoice=SCISSORS;

	return pChoice;

}




And here is the header and struct/enum definitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum gameChoice{ROCK,PAPER,SCISSORS}; //game choices

struct PlayerScores{
	int p1Score;
	int p2Score;
};

struct HighScore{ //Single score in highscores
	string name;
	int score;
};

gameChoice getChoice(); //Gets user choice

gameChoice cpuChoice(); //gets cpu choice



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
	//Constants
	const string itemName[3] = {"Rock","Paper","Scissors"};

	//Variables
	int menu;
	string name;

	//Scores
	HighScore currentScores[3];
	PlayerScores activeScores={0,0};
	
	//Txt File
	ofstream outFile;
	GetHighscores(currentScores, 3);

	cout << "Welcome to Rock, Paper, Scissors." << endl;

	//Get name
	cout << "Enter your name: ";
	getline(cin,name);

.......


Sorry for the length. I tried to leave out anything unnecessary.

It would be great if I can get some kind of idea of how to fix this. Thank you in advance.
Last edited on
I can't tell where the bug is from the code you've posted, but it's pretty clear that you're trying to dereference an uninitialized pointer somewhere.
That's as best as I can narrow it down from the information you've provided.
Thank you for the reply. I didn't actually use * to declare any pointers anywhere, so would it be correct to say that it is probably stemming from a reference parameter somewhere?
Last edited on
Yes. References often get compiled into equivalent pointer-based code.
The error does not occur if the line


activeScores.p1Score++;


is removed.


Does that open any more possibilities?
Check how it's being initialized.
I found the problem. The function UpdateScores compared that value to the current highscore spot, and if it was higher, it entered a for loop to replace the current highscore(s) with the new one.


The error was in the for loop which only happened if that value was incremented.

I made two mistakes. The first was getting the number of elements in an array mixed up with the indices, forgetting to ad a "-1" to the index of one.

The second was putting "++" where "--" should have gone in one of the for loops.


That was a lot of headache for a small problem, but that's programming for you.


Thanks for all the help.
Topic archived. No new replies allowed.