Search code examples
cscanfc-stringschess

C sscanf not working correctly with char pointer


I'm trying to parse a FEN using sscanf in C. I have the following code:

int main() {
  char side, pos[128], castle[4], enpas[2];
  int halfMove, fullMove;
  const char fen[] = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
  const int res = sscanf(fen, "%s %c %s %s %d %d", pos, &side, castle, enpas, &halfMove, &fullMove);
  printf("%d\n", res);
  printf("%s %c %s %s %d %d\n", pos, side, castle, enpas, halfMove, fullMove);
  return 0;
}

When I run this code I get the following expected result:

6
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1

However when I change the FEN string from a char array to a char pointer like so

const char *fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

I get the following result:

6
 w KQkq - 0 1

as if the first part of the string is ignored. Why is this happening? I'm using GCC 10.1.0.


Solution

  • The problem is that you are missing the point that C-strings are null-terminated.

    Your declarations

    char side, pos[128], castle[4], enpas[2];
    

    does not leave space for '\0' to be appended at the end of those strings after reading them from the FEN.

    As a result, it is undefined behaviour.

    This will solve the problem:

    char side, pos[129], castle[5], enpas[3];