Search code examples
cbuffer-overflowkernighan-and-ritchie

Custom get line input function


I am reading over the K&R book, and am a little stuck.

What is wrong with the following?

void getInput(int* output) {
   int c, i;
   for(i=0; (c = getchar()) != '\n'; i++)
     output[i] = c; // printf("%c", c) prints the c value as expected
   output[++i] = '\0';
}

When I run the program it never gets out of the loop and I have to Ctrl+C to exit. However if I replace the fifth line with printf("%c", c);, it prints out all the input just fine after hitting enter and creating the new line.


Solution

  • What is wrong with the following?

    1. void getInput(int* output) {
    

    Why is the input argument an int* when what you want to store in an array of characters? Probably

    void getInput(char* output) {
    

    is better.

    Also, how do you know that the output pointer is pointing somewhere where you hold enough memory to write the user's input? Maybe you must have the maximum buffer length as an extra parameter to avoid buffer overflow errors as PW pointed out.

    5.   output[++i] = '\0';
    

    i has already been incremented an extra time inside the for loop, so you can just do:

    output[i] = '\0';
    

    Other than these, the program runs fine and outputs what we input until return.

    FWIW, I tested it by calling it like so:

     int main(void)
    {
        char o[100];
        getInput(o);
        printf("%s", o);
        return 0;
    }