Search code examples
cscanfbuffer-overflow

How to prevent buffer overflow when we recursively ask for input if input is not valid


Have to take a input string of size 5. Also have to check for validity in some unrelated sense. If the input is not valid user is prompted to input again.

Using the scanf("%4s", input); But if the user inputs suppose string of 8 characters, the scanf just scans the last 4 chars still in the buffer before asking for actual user input.

I tried making a buffer variable that stores the input before passing it to the target var.


Solution

  • How to prevent buffer overflow when we recursively ask for input if input is not valid?

    1. When seeking an input of up to n characters, (which is n + 1 characters when one counts the Enter or '\n'), read at least a line of at least n + 1 characters. With fgets(), that needs to fit in a buffer of size n + 2. The extra 1 is to store the appended null character.
    #define STRING_LENGTH_MAX 5
    
    char buf[STRING_LENGTH_MAX + 2];
    for (;;) {
      if (fgets(buf, sizeof buf, stdin) == NULL) {
        // There is no more input from stdin.
        // TBD code - perhaps quit?
      }
      ...
    
    1. Search the string saved for a '\n'. If found, lop it off and continue. If not found and line is long, read the rest of the line. Discard all and loop back (not recurse) to step 1.
      buf[strcspn(buf, "\n")] == '\0'; // Lop off a potential '\n'.
      if (strlen(buf) <= STRING_LENGTH_MAX) {
        // Perform other validation tests on `buf`.
        // Otherwise ...
        break;
      }
      // Read and toss rest of line.
      int ch;
      while ((ch = getchar()) != '\n' && ch != EOF) {
        ;
      }
    }
    
    1. Consider putting this all into a helper function.