I'm having an issue with a smart contract I've created where variables are being affected by a function that does not access them. I am using Remix to test this.
//Solidity Version
pragma solidity ^0.4.0;
//Contract Code
contract TicTacToe{
//Struct for cell
struct Cell {
uint row;
uint column;
address played;
}
//Struct for game board
struct GameBoard {
bool gameWon;
address _player1;
address _player2;
Cell[] board;
}
//These variables are being affected due to newGame();
uint private numberOfGames = 0; //I set this to private and created a getter (getGameNum()), but same occurs if public.
GameBoard[] public _games; //This is also being affected - newGame() will fill the array, even though only one item is being pushed.
//Publig getter for numberOfGames uint.
function getGameNum() public returns(uint){
return numberOfGames;
}
//Function that creates an array. This will eventually add it to _games but until issue is resolved, I'm leaving it.
function newGame() public {
//Create a temporary board (to be pushed later)
GameBoard tempBoard;
//Fill attributes of board
tempBoard._player1 = msg.sender;
tempBoard._player2 = msg.sender;
tempBoard.gameWon = false;
uint counter = 0;
//For each row
for (uint row = 1; row <= 3; row++) {
//For each column
for (uint column = 1; column <= 3; column++) {
tempBoard.board.length++;
tempBoard.board[counter].row = row;
tempBoard.board[counter].column = column;
tempBoard.board[counter].played = 0x0;
counter++;
}
}
}
}
"numberOfGames" is correctly set to 0 on contract creating (you can verify this using getGameNum() ). However, when newGame() is called, the value is changed to 295530007198671819985454669347690311693110848207872. Likewise, the _games array is filled when the newGame() function is called, even when the function doesn't interact with that array.
Any reason why this would be happening?
GameBoard private tempBoard;
, keeping it in storage, rather than declaring one in your functionGameBoard tempBoard;
, it seems to solve the problem. I'm not saying this is a good solution to your problem, but consider reading into storage vs memory, and value vs reference types.