Malloc and scanf

前端 未结 5 1908
攒了一身酷
攒了一身酷 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:56

    First, the errors that was keeping your program from working: scanf(3) takes a format-string, just like printf(3), not a string to print for the user. Second, you were passing the address of the pointer toParseStr, rather than the pointer toParseStr.

    I also removed the needless cast from your call to malloc(3).

    An improvement that your program still needs is to use scanf(3)'s a option to allocate memory for you -- so that some joker putting ten characters into your string doesn't start stomping on unrelated memory. (Yes, C will let someone overwrite almost the entire address space with this program, as written. Giant security flaw. :)

    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
      char *toParseStr = malloc(10);
      printf("Enter a short string: ");
      scanf("%s",toParseStr);
      printf("%s\n",toParseStr);
      return 0;
    }
    

提交回复
热议问题