The getline function getline declared as follows.
ssize_t getline (char **lineptr, size_t *n, FILE *stream):
Therefore, your code has undefined behavior, since the second argument is a null pointer.
read = getline(&line, 0, stdin); ^^^
And in this sentence the format string is incorrect
printf("line length = %zu\n", read); ^^^^
since the read variable in your program is of type int , not size_t , as it should be.
If the getline function getline value -1 , for example, when the end-of-file event occurs, however, the contents of the buffer in your program are still output to the console before this event is recognized in the while condition.
char *line = NULL; int read = 0; while (read != -1) { puts("enter a line"); read = getline(&line, 0, stdin); // read уже равно -1, но буфер выводится на консоль printf("line = %s", line); printf("line length = %zu\n", read); //...
To interrupt line input, you can type Ctrl + z in Windows, or Ctrl + d in Unix. You can also enter an agreement that if the user enters a blank line by simply pressing the Enter key, this is also considered a sign of the end of the input.
The program may, for example, look like this.
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> int main( void ) { char *line = NULL; size_t size = 0; while ( 1 ) { size_t n; printf( "Enter a line (empty string - exit): "); if ( ( n = getline( &line, &size, stdin ) ) < 0 || *line == '\n' ) break; printf( "line = %s", line ); printf( "line length = %zu\n", n ); puts(""); } free( line ); return 0; }
The dialogue with the program can be
Enter a line (empty string - exit): Hello daniil.vorobjew2017 line = Hello daniil.vorobjew2017 line length = 27 Enter a line (empty string - exit): Have a nice day line = Have a nice day line length = 16 Enter a line (empty string - exit):