How do I properly free memory related to getline() function?
Asked Answered
S

1

21

I just started programming and have a beginner question, I want to write a function to read a file with unknown length line by line. Since I wouldn't know the length of each line so I used getline() function:

void readDict(FILE *dict_file){
  //Read dic 
  char *line;
  size_t len = 0, read;
  while((read = getline(&line, &len, dict_file))!=-1){
    check(line); 
  }
  free(line);
  return;
}

Since getline() is kind of similar to malloc() and realloc() a string, so if I keep using this function to read a lot of line with unknown length, would I get a memory leak or out of memory?

Subarctic answered 27/2, 2017 at 6:6 Comment(5)
Based on the documentation, you need to malloc memory for line before calling getline.Biographer
@Biographer Nope, it's not a must.Traumatism
@SouravGhosh how would you do it without allocating memory?Biographer
@Biographer "If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program."Traumatism
@SouravGhosh didn't know that, thanks!Biographer
T
32

First of all, you should initialize lineptr to NULL. Without a proper initialization, lineptr will contain indeterminate value, which makes lineptr to point to invalid memory location and later in process, it will invoke undefined behavior while trying to allocate (realloc()) appropriate amount of memory.

Then, as per the man page,

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

So, as long as you pass the same *lineptr, you should be OK if you free() only once in the end.

Traumatism answered 27/2, 2017 at 6:13 Comment(3)
So when I initialize the pointer it should be {char *line=NULL;} ?Subarctic
@GhostKidYao Yep.Traumatism
Ok, Thank you for your answer!Subarctic

© 2022 - 2024 — McMap. All rights reserved.