I want to read multiple lines from a text file by a loop, but I always get Conditional jump or move depends on uninitialised value(s)
error in my getline()
line.
My code:
char *string;
size_t len = 0;
while (getline(&string, &len, fileStream) != -1) { // error happens this line
// do something
}
free(string);
fclose(fileSream);
I tried but failed to fix it. Any solutions will be appreciated.
You need to do either of below.
set char *string = NULL;
and len
to 0
. [[ Preferred Method ]]
allocate memory to char *string
and send the size of allocated memory using len
.
Related quotes from man page for referrence
If *lineptr is set to NULL and *n is set 0 before the call, then
getline() will allocate a buffer for storing the line. This buffer
should be freed by the user program even if getline() failed.
Alternatively, before calling getline(), *lineptr can contain a
pointer to a malloc(3)-allocated buffer *n bytes in size. If the
buffer is not large enough to hold the line, getline() resizes it
with realloc(3), updating *lineptr and *n as necessary.