How do I properly free memory related to getline() function? How do I properly free memory related to getline() function? c c

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


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.