Learn C
#include "ioformatting/getline_posix.h"

Dynamic Line Input with getline (POSIX) in C

#concept

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.

#how it works
1

Start NULL, grow automatically

char *line = NULL; size_t cap = 0; — getline allocates and reallocates the buffer itself as lines demand.

2

Count or -1

Returns characters read including newline, or -1 at EOF/error — feof vs ferror explains which.

3

Strip and free

Remove the kept newline as with fgets; free(line) once when finished — one allocation per stream session.

4

Know the portability line

POSIX systems (Linux, macOS) provide it; strict ISO-only targets stick with fgets plus manual growth.

#example
#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;
}
Output
got [any length works]
1NULL buffer plus zero capacity tells getline to manage allocation entirely.
2Any length line arrives whole — no truncation point exists to hit.
3Strip, print bracketed, free — complete dynamic-line lifecycle.
#use cases
Reading arbitrarily long lines without buffer-size anxiety
REPLs and config readers on POSIX systems
Stripping newlines identically to fgets-based code
Falling back to fgets for strictly portable builds

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.