What is the purpose of the second parameter in getline?

1.1k views Asked by At
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char* buffer = malloc(100 * sizeof(char));
    size_t n = 3;

    getline(&buffer, &n, stdin);
    printf("%s\n", buffer);
    free(buffer);
}

I thought the second parameter in getline, size_t *n, was to limit the number of characters read. But when I tried with larger input, it still read all the input. I searched in the man pages and online but could not find an answer. Could anyone explain it for me?

1

There are 1 answers

2
David Titarenco On BEST ANSWER

From getline man pages:

Given ssize_t getline(char **lineptr, size_t *n, FILE *stream);

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.)

Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

Emphasis mine. In short, n is updated to make sure the line fits.