How to read the standard input into string variable until EOF in C?

后端 未结 5 2161
北恋
北恋 2020-12-05 08:44

I am getting \"Bus Error\" trying to read stdin into a char* variable. I just want to read whole stuff coming over stdin and put it fi

5条回答
  •  青春惊慌失措
    2020-12-05 09:20

    The problem here is that you are referencing a pointer variable that no memory allocated via malloc, hence the results would be undefined, and not alone that, by using strcat on a undefined pointer that could be pointing to anything, you ended up with a bus error!

    This would be the fixed code required....

    char* content = malloc (100 * sizeof(char));
    char c;
    if (content != NULL){
       content[0] = '\0'; // Thanks David!
       while ((c = getchar()) != EOF)
       {
           if (strlen(content) < 100){
               strcat(content, c);
               content[strlen(content)-1] = '\0';
           }
       }
    }
    /* When done with the variable */
    free(content);
    

    The code highlights the programmer's responsibility to manage the memory - for every malloc there's a free if not, you have a memory leak!

    Edit: Thanks to David Gelhar for his point-out at my glitch! I have fixed up the code above to reflect the fixes...of course in a real-life situation, perhaps the fixed value of 100 could be changed to perhaps a #define to make it easy to expand the buffer by doubling over the amount of memory via realloc and trim it to size...

提交回复
热议问题