Reputation: 825
#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?
Upvotes: 5
Views: 1235
Reputation: 33396
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.
Upvotes: 6