Dynamic Line Input with getline (POSIX) in C
POSIX getline() reads a full line into a malloc'd buffer that grows as needed: char *line = NULL; size_t cap = 0; ssize_t n = getline(&line, &cap, stdin); — no size guessing, no truncation, arbitrarily long lines handled. The buffer starts NULL (library allocates) and you free(line) when done.
Return value is the character count or -1 at EOF/error (distinguish with feof/ferror). The trailing newline is kept (strip it like fgets). Standard C lacks this — it is POSIX (and C23-adjacent practice) — so guard portability needs or fall back to fgets for strict ISO code.
Start NULL, grow automatically
char *line = NULL; size_t cap = 0; — getline allocates and reallocates the buffer itself as lines demand.
Count or -1
Returns characters read including newline, or -1 at EOF/error — feof vs ferror explains which.
Strip and free
Remove the kept newline as with fgets; free(line) once when finished — one allocation per stream session.
Know the portability line
POSIX systems (Linux, macOS) provide it; strict ISO-only targets stick with fgets plus manual growth.
#include <stdio.h>#include <stdlib.h>#include <string.h> int main(void) { char *line = NULL; size_t cap = 0; if (getline(&line, &cap, stdin) > 0) { line[strcspn(line, "\n")] = 0; printf("got [%s]\n", line); } free(line); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.