I am writing a chess engine and to get pseudo-random moves, I pass a move generation function an array to fill. Here is some code:
...
else if(pstrcmp(input, (char*)"check", 5)){
int checkIndex = getIndex(input[6], input[7] - 49);
printf("checkindex %i\n", checkIndex);
if(!(checkIndex < 0 || checkIndex > 127)){
//we've received a valid check
struct m mUn[MOVE_BUFF];
gen_psm(checkIndex, mUn);
int i = 0;
while(mUn[i].start != mUn[i].end && i < MOVE_BUFF){
printf("%s\n", GSQ(mUn[i].end));
i++;
}
}
}
...
The first line is just some input checking. The meat of the code is between struct m mUn[MOVE_BUFF]
and the while loop. So I create a struct m
array, which I created and it holds a few ints that specifies a specific move, and then I pass it to gen_psm
which takes an index of the square to check and an array to fill. It fills the array with valid moves for the piece located at the index. Fine and dandy for the first move. Then I try the second move, and I find that the array still has the data in it from the first move, even though I have long exited the scope of the mUn where I declared it. Is it some nature of structs that it retains its data? Do I need to 0 fill the whole thing (it seemed to be full of 0's when I tried it). If I need to 0 fill it, is there a faster way (if I have to 0 fill it several 100 million times, that's a problem)?
There is nothing in the standard that guarantees that the memory of a local variable which has left scope will be changed, it is simply undefined behavior to read it. The compiler may zero it, it may not, it may insert a smiley into the beginning of it. It is unspecified as to what will happen to that memory location after the variable is out of scope.
Simply declaring an array ensures that space will be reserved for it, but it does not initialize each member. You can memset
it or just initialize each one in a loop.