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?
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 amalloc()
-allocated buffer*n
bytes in size. If the buffer is not large enough to hold the line,getline()
resizes it withrealloc()
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With