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

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 block are definitely lost ...

... getline (getline.c: 34)

I can fix this by adding free() :

 while ((read = getline(&line, &len, fp)) != -1) { /*Do something*/ } free(line); 

My question is : Why getline allocate memory for line when it fails? And why don't I need free(line) for every getline call?

+7
source share
2 answers

The setup is such that you can pass the previously allocated memory block getline() , and it will allocate more ( realloc() ) if necessary. (Or you can start with the lack of allocated memory, as here.) It can report an error or EOF, but does not free up the space that was allocated, so you need to free it. If the file is an empty file and you start without data, you may not get the allocated space; on the other hand, it may allocate some space before trying to get data from a file.

But you know that if the line pointer is not null, it has been allocated and needs to be freed.

+9
source

getline may fail in several different ways and may or may not reallocate memory one or more times when it does not work. To be consistent, it never frees memory - see One Possible Implementation at http://www.opensource.apple.com/source/cvs/cvs-19/cvs/lib/getline.c

This consistency simplifies the implementation for both the implementation and the caller ... you always just clear the line, not check the error code to see if it is free.

+2
source

All Articles