cprintfgetchar

Strange printf not working after a getchar and getchar skipping


I'm getting crazy with C. I'm programming with JavaScript, Ruby, Python, PHP, Lua, even Java... Recently, I tried to program a simple Read-Eval-Print-Loop in C. And I have a very strange behavior with this simple, basic, code, on Windows 10. This code is compiled with the standard toolchain of Visual Studio.

  1. sometimes (it is impossible to predict), the reading of the string is skipped. I guessed there must be some garbage in the stdin but I can't flush it with fflush, right?
  2. everytimes, all the printf AFTER the loop on getchar are not working. Nothing is displayed. I put \n and fflush to no avail.

Help me, you are my only hope.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
    const size_t line_length = 1024;
    char * line = malloc(line_length * sizeof(char));
    memset(&line, '\0', line_length);
    char c;
    unsigned short count = 0;
    // fflush(stdin); // tried this, same thing
    printf("Enter: ");
    while ((c = getchar()) != '\n' && c != EOF && count < line_length - 1) {
        line[count] = c;
        count += 1;
    }
    printf("Count : %d\n", count);
    printf("%s\n", line);
    printf("End of program.\n");
    fflush(stdout);
    free(line);
    return EXIT_SUCCESS;
}

Expected output:

Enter: hello
Count : 5
hello

Actual output (1):

Enter: hello 

Actual output (2):


Solution

  • There are several issues with your code:

    Corrected code, see my comments starting with ///

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>                      /// added
    
    int main(int argc, char* argv[])
    {
      const size_t line_length = 1024;
      char* line = malloc(line_length);
      memset(line, '\0', line_length);      /// removed & 
      int c;                                /// int instead of char
      unsigned short count = 0;
      // fflush(stdin);                     /// fflush(stdin); is UB
      printf(">>> ");
      while ((c = getchar()) != '\n' && c != EOF && count < line_length - 1) {
        line[count] = c;
        count += 1;
      }
      printf("Count : %d\n", count);
      printf("%s\n", line);
      printf("End of program.\n");
      fflush(stdout);
      free(line);
      return EXIT_SUCCESS;
    }