Skip to content
Advertisement

Variable reset after scanf

I wrote the below function :

typedef enum {GREEN,BLACK, WHITE} color;

void StartGame(Piece board[8][8])
{
    color currentPlayer=WHITE;
    char location[2];
    int gameover=1;
    while(gameover)
    {
        printf("%dn",currentPlayer);

        if(currentPlayer==WHITE)
            printf(BOLDWHITE"White: Please select a piece:n");
        else
            printf(BOLDBLACK"Black: Please select a piece:n");

        printf("%dn",currentPlayer);

        scanf("%s",location);

        printf("%dn",currentPlayer);
        if(currentPlayer==WHITE)
            currentPlayer=BLACK;
        else
            currentPlayer=WHITE;

    }
} 

I print the currentPlayer on any level to see what’s going on -> here what I get:

2
White: Please select a piece:
2
a1
0
2
White: Please select a piece:
2

Why the current player is 0 after scanf? I didn’t touch it.

Advertisement

Answer

The buffer location has only room for 2 characters and scanf puts an extra NUL character at end. Therefore you have a stack corruption issue. Just give more room to location, for example:

char location[8];

EDIT

Since you just want to read a string, I recommend you using fgets, which allows you to limit the number of read characters from the input string. Thus, my code would look like this:

char location[8];
...
fgets(location, sizeof(location), stdin); //instead of scanf, fgets reads at most one less than buffer's size characters.

You only have to worry about the fact that fgets puts a final end line character (n) at the end, but this should not be a deal if you just process the 2 first characters of the string.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement