Do I need to call free() after a failed getline()?

c, malloc

Solution

The setup is such that you can pass a previously allocated block of memory to `getline()`, and it will allocate more (`realloc()`) if it needs it. (Or you can start with no memory allocated, as here.) It can report failure or EOF, but doesn't release the space that was allocated — hence you need to free it. If the file is an empty file and you start off with no data, you might not get any space allocated; on the other hand, it may have allocated some space before it attempts to get data from the file.

But you know that if the `line` pointer is not null, it was allocated and must be freed.

Problem

The following block causes a memory leak: ``` FILE *fp = fopen(path, "r"); char *line = NULL; size_t len = 0; ssize_t read = -1; while ((read = getline(&line, &len, fp)) != -1) { /*Do something*/ } ``` 120 bytes in 1 blocks are definitely lost... ...getline (getline.c:34) I can fix this by adding a `free()`: ``` while ((read = getline(&line, &len, fp)) != -1) { /*Do something*/ } free(line); ``` My question is: Why does `getline` allocate memory for `line` when it fails? And why do I not need to `free(line)` for every call to `getline`?

Original source