Malloc and scanf

前端 未结 5 1967
攒了一身酷
攒了一身酷 2021-01-18 19:19

I\'m fairly competent in a few scripting languages, but I\'m finally forcing myself to learn raw C. I\'m just playing around with some basic stuff (I/O right now). How can

5条回答
  •  遇见更好的自我
    2021-01-18 19:52

    Using scanf() (or fscanf() on data you don't control) with a standard "%s" specifier is a near-certain way to get yourself into trouble with buffer overflows.

    The classic example is that it I enter the string "This string is way more than 10 characters" into your program, chaos will ensue, cats and dogs will begin sleeping together and a naked singularity may well appear and consume the Earth (most people just state "undefined behaviour" but I think my description is better).

    I actively discourage the use of functions that cannot provide protection. I would urge you (especially as a newcomer to C) to use fgets() to read your input since you can control buffer overflows with it a lot easier, and it's more suited to simple line input than scanf().

    Once you have a line, you can then call sscanf() on it to your heart's content which, by the way, you don't need to do in this particular case since you're only getting a raw string anyway.

    I would use:

    #include 
    #include 
    #include 
    
    #define BUFFSZ 10
    
    int main(int argc, char *argv[]) {
      char *toParseStr = malloc(BUFFSZ+2);
      if (toParseStr == NULL) {
          printf ("Could not allocate memory!\n");
          return 1;
      }
      printf ("Enter a string: ");
      if (fgets (toParseStr, BUFFSZ+2, stdin) == NULL) {
          printf ("\nGot end of file!\n");
          return 1;
      }
      printf("Your string was: %s",toParseStr);
      if (toParseStr[strlen (toParseStr) - 1] != '\n') {
          printf ("\nIn addition, your string was too long!\n");
      }
      free (toParseStr);
      return 0;
    }
    

提交回复
热议问题